You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过字符串"Account.Number"获取接口属性值遇空引用异常求助

问题排查与解决
  • 核心错误:你混淆了字段(Field)和属性(Property)。Number是接口定义的属性,而GetField方法只能查找类/接口中的字段成员,找不到对应成员就会返回null,后续调用ToString()自然触发“未将对象引用设置到对象的实例”错误。
  • 正确实现步骤:
    1. 使用GetProperty替代GetField获取属性信息
    2. 通过PropertyInfo.GetValue()方法获取属性的实际值
    3. (可选)如果属性是接口的显式实现,需要直接从接口类型中获取属性定义

基础可行代码

// 先确保Account实例不为null
if (this.Account == null)
{
    MessageBox.Show("Account实例未初始化");
    return;
}

// 获取属性信息并取值
var numberProperty = this.Account.GetType().GetProperty("Number");
if (numberProperty != null)
{
    var numberValue = numberProperty.GetValue(this.Account);
    MessageBox.Show(numberValue.ToString());
}
else
{
    MessageBox.Show("未找到Number属性");
}

处理显式接口实现的情况

如果Number是通过显式实现接口的方式定义的(比如int API.Internals.IAccount.Number { get; }),直接从实例GetType()获取会失败,需要指定接口类型:

var numberProperty = typeof(API.Internals.IAccount).GetProperty("Number");
if (numberProperty != null)
{
    var numberValue = numberProperty.GetValue(this.Account);
    MessageBox.Show(numberValue.ToString());
}

内容的提问来源于stack exchange,提问作者another J.Doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 03:09:55