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

时间:2009-12-12 20:10:31

标签: c# 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());

}

3 个答案:

答案 0 :(得分:3)

这样的方法怎么样:

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);

答案 1 :(得分:1)

阅读错误消息。

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

答案 2 :(得分:0)

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