2009-12-12 2 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); 
관련 문제