【问题标题】:C# Reflection GetField().GetValue()C# 反射 GetField().GetValue()
【发布时间】: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


【解决方案1】:

将 {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"];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    相关资源
    最近更新 更多