[英]C# Reflection 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; }
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"];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.