簡體   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