通过双嵌套类的反射获取价值

时间:2015-11-06 01:36:29

标签: c# reflection

目前我试图从嵌套类中获取属性的值。不幸的是,我获得的参数为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()中的对象?

1 个答案:

答案 0 :(得分:3)

您需要从ic

获取FieldInfo的值
object ic = ic_field.GetValue(o);

然后将其传递给test_prop.GetValue

string test2 = (string)test_prop.GetValue(ic, null);
相关问题