2012-05-31 101 views
2

美好的一天,如果我擁有該屬性的自定義屬性值,我該如何獲取類的屬性名稱?當然還有自定義屬性名稱。按屬性值獲取屬性名稱

+2

請解釋更多,你的問題現在並不十分清楚,並且可能會被關閉。 –

回答

0

通過自定義屬性獲取屬性名稱:

public static string[] GetPropertyNameByCustomAttribute 
     <ClassToAnalyse, AttributeTypeToFind> 
     (
     Func<AttributeTypeToFind, bool> attributePredicate 
    ) 
     where AttributeTypeToFind : Attribute 
    { 
     if (attributePredicate == null) 
     { 
     throw new ArgumentNullException("attributePredicate"); 
     } 
     else 
     { 
     List<string> propertyNames = new List<string>(); 

     foreach 
     (
      PropertyInfo propertyInfo in typeof(ClassToAnalyse).GetProperties() 
     ) 
     { 
      if 
      (
      propertyInfo.GetCustomAttributes 
      (
       typeof(AttributeTypeToFind), true 
      ).Any 
      (
       currentAttribute =>     
       attributePredicate((AttributeTypeToFind)currentAttribute) 
      ) 
     ) 
      { 
      propertyNames.Add(propertyInfo.Name); 
      } 
     } 

     return propertyNames.ToArray(); 
     } 
    } 

測試夾具:

public class FooAttribute : Attribute 
{ 
    public String Description { get; set; } 
} 

class FooClass 
{ 
    private int fooProperty = 42; 

    [Foo(Description="Foo attribute description")] 
    public int FooProperty 
    { 
    get 
    { 
     return this.fooProperty; 
    } 
    } 

} 

測試用例:

// It will return "FooProperty" 
GetPropertyNameByCustomAttribute<FooClass, FooAttribute> 
( 
    attribute => attribute.Description == "Foo attribute description" 
); 


// It will return an empty array 
GetPropertyNameByCustomAttribute<FooClass, FooAttribute> 
( 
    attribute => attribute.Description == "Bar attribute description" 
); 
+0

這與屬性有什麼關係?當然,問題並不清楚,但答案中甚至沒有「屬性」一詞。 – aquinas

+0

不知道爲什麼這是downvoted。我的問題在於OP詢問如何檢索給定對象的可調用屬性列表。考慮到這個問題中缺乏信息,這個答案似乎是正確的。 –

+0

很明顯,我知道他想知道如何使用Reflection API,因爲我聽說過有關反射API的其他相關問題,我知道對於不知道此API的人來說,解釋他的意圖是非常困難的。 – fsenart