2012-09-04 59 views
3

我有一個包含一些屬性的類。一些特定的屬性用一個屬性裝飾。例如:通過屬性的特定屬性和調用方法來過濾類實例的屬性

public class CoreAddress 
{ 
    private ContactStringProperty _LastName; 

    [ChangeRequestField] 
    public ContactStringProperty LastName 
    { 
     //ContactStringProperty has a method SameValueAs(ContactStringProperty other) 
     get { return this._LastName; } 
    } 
    ..... 
} 

我想在我的類中的方法,它通過我的這個類的所有屬性散步,過濾一個與此自定義屬性和調用發現特性的成員。這是我到目前爲止有:

foreach (var p in this.GetType().GetProperties()) 
     { 
      //checking if it's a change request field 
      if (p.GetCustomAttributes(typeof(ChangeRequestFieldAttribute), false).Count() > 0) 
      { 

       MethodInfo method = p.PropertyType.GetMethod("SameValueAs"); 
       //problem here   
       var res = method.Invoke(null, new object[] { other.LastName }); 

      } 

     } 

如果此方法是屬性的實例方法,我必須提供一個目標(而不是空在代碼中)。如何在運行時獲取此類實例的特定屬性?

+0

如果你知道關於該類的所有信息,爲什麼要使用反射?或者你想處理後代的一些屬性? –

+0

它實際上用於避免大量容易出錯的手動屬性檢查,此外,當開發人員添加具有此屬性的屬性時,它將自動包含在上述方法中。 – hoetz

回答

1

由於您已擁有PropertyInfo,因此您可以撥打GetValue method。所以...

MethodInfo method = p.PropertyType.GetMethod("SameValueAs"); 
//problem solved 
var propValue = p.GetValue(this); 

var res = method.Invoke(propValue, new object[] { other.LastName }); 
+0

D'oh,謝謝! – hoetz

0

使用PropertyInfo可以獲得您需要的任何財產的價值。

0

只要將屬性值拿出來並像通常一樣使用它。

foreach (var p in type.GetProperties()) 
{ 
     if (p.GetCustomAttributes(typeof(ChangeRequestFieldAttribute), false).Count() > 0) 
     { 

       //just get the value of the property & cast it. 
       var propertyValue = p.GetValue(<the instance>, null); 
       if (propertyValue !=null && propertyValue is ContactStringProperty) 
       { 
        var contactString = (ContactStringProperty)property; 
        contactString.SameValueAs(...); 
       } 
     } 
    }