[英]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.