微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C# 反射 GetField().GetValue()

如何解决C# 反射 GetField().GetValue()

鉴于以下内容

List<T> someList;

其中 T 是某个类的类型:

public class Class1
{
  public int test1;
}

public class Class2
{
  public int test2;
}

您将如何使用反射来提取存储在每个列表项中的 test1/test2 的值? (提供了字段名称

我的尝试:

print(someList[someIndex]
.GetType()
.GetField("test1")
.GetValue(someList) // this is the part I'm puzzled about. What kind of variable should i pass here?

我遇到的错误 “未将对象引用设置为对象的实例”,根据微软文档,我应该传递给 GetValue 的变量是“将返回其字段值的对象”。 - 这就是我正在做的事情。

感谢阅读!

解决方法

将 {get;set;} 添加到您的属性中 public int test1 { get; set; }

var t = someList[0].GetType().GetProperty("test1").GetValue(someList[0],null);

我建议你可以使用这个方法

public class Class1
{
    public int test1 { get; set; }
    public object this[string propertyName]
    {
        get { return this.GetType().GetProperty(propertyName).GetValue(this,null); }
        set { this.GetType().GetProperty(propertyName).SetValue(this,value,null); }
    }
}

var value = someList[0]["test1"];

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。