繁体   English   中英

使用反射从嵌套类中获取价值

[英]Get value from nested class using reflection

public class CustomProperty<T>
{
    private T _value;

    public CustomProperty(T val)
    {
        _value = val;
    }
    public T Value
    {
        get { return this._value; }
        set { this._value = value; }
    }
}

public class CustomPropertyAccess
{
    public CustomProperty<string> Name = new CustomProperty<string>("cfgf");
    public CustomProperty<int> Age = new CustomProperty<int>(0);
    public CustomPropertyAccess() { }
}

//I jest beginer in reflection. 

//How can access GetValue of  CPA.Age.Value using fuly reflection


private void button1_Click(object sender, EventArgs e)
{
   CustomPropertyAccess CPA = new CustomPropertyAccess();
   CPA.Name.Value = "lino";
   CPA.Age.Value = 25;

//I did like this . this is the error   “ Non-static method requires a target.”
MessageBox.Show(CPA.GetType().GetField("Name").FieldType.GetProperty("Value").GetValue(null     ,null).ToString());

}

这样的方法怎么样:

public Object GetPropValue(String name, Object obj) {
    foreach (String part in name.Split('.')) {
        if (obj == null) { return null; }

        Type type = obj.GetType();
        PropertyInfo info = type.GetProperty(part);
        if (info == null) { return null; }

        obj = info.GetValue(obj, null);
    }
    return obj;
}

并像这样使用它:

Object val = GetPropValue("Age.Value", CPA);

阅读错误消息。

非静态方法和属性与类的实例相关联-因此,当您尝试通过反射访问它们时,您需要提供一个实例。

GetProperty.GetValue方法中,您需要指定要为其获取属性值的对象。 在您的情况下,它将是: GetValue(CPA ,null)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM