2012-05-31 257 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