[英]Get value via Reflection from double nested class
目前,我正在嘗試從嵌套類中獲取屬性的值。 不幸的是我將參數作為object
。 我知道內部結構,但我不知道該如何到達酒店。
為了便於測試,我准備了一些代碼行:
namespace ns{
public class OuterClass{
public InnerClass ic = new InnerClass();
}
public class InnerClass {
private string test="hello";
public string Test { get { return test; } }
}
}
直接調用它很容易:
var oc = new ns.OuterClass();
string test = oc.ic.Test;
但是,當我嘗試通過反射獲取值時,我遇到了System.Reflection.TargetException
:
object o = new ns.OuterClass();
var ic_field=o.GetType().GetField("ic");
var test_prop = ic_field.FieldType.GetProperty("Test");
string test2 = test_prop.GetValue(???).ToString();
我必須在GetValue()
使用什么作為對象?
您需要從FieldInfo
獲取ic
的值:
object ic = ic_field.GetValue(o);
然后將其傳遞給test_prop.GetValue
:
string test2 = (string)test_prop.GetValue(ic, null);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.