按属性值获取属性名称

时间:2012-05-31 14:22:18

标签: c# attributes

美好的一天,如果我有该属性的自定义属性值,我怎样才能获得类的属性名称?和自定义属性名称当然。

1 个答案:

答案 0 :(得分: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"
);