通过双重嵌套的反射获取价值 class
Get value via Reflection from double nested class
目前我正在尝试从嵌套的 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);
目前我正在尝试从嵌套的 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);