目前,我正在尝试从嵌套类中获取属性的值。不幸的是,我得到了一个作为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()中的对象,我必须使用什么
发布于 2015-11-06 01:39:56
您需要从ic获取FieldInfo的值。
object ic = ic_field.GetValue(o);然后你把它传递给test_prop.GetValue
string test2 = (string)test_prop.GetValue(ic, null);https://stackoverflow.com/questions/33558025
复制相似问题