【发布时间】:2021-09-26 12:28:35
【问题描述】:
鉴于以下情况:
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 的变量是“将返回其字段值的对象”。 - 这就是我正在做的事情。
感谢阅读!
【问题讨论】:
-
应该是
.GetValue(someList[someIndex]) -
Documentation says: "
obj对象:将返回其字段值的对象。"换句话说,你想要获取的字段的对象,类似于obj.test1,所以在这种情况下是someList[someIndex]
标签: c# reflection getvalue