从双嵌套类中通过反射获取值

本文关键字:反射 获取 嵌套 | 更新日期: 2023-09-27 18:20:51

当前我正在尝试从嵌套类中获取属性的值。不幸的是,我得到了一个参数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);