2009-12-12 54 views
0
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()); 

} 

回答

1

閱讀錯誤消息。

非靜態方法和屬性與一個類的實例相關聯 - 所以當你試圖通過反射訪問它們時你需要提供一個實例。

0

GetProperty.GetValue方法中,您需要指定要獲取其屬性值的對象。對你來說,這將是:GetValue(CPA ,null)

2

怎麼樣這樣的方法:

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