2

美好的一天,如果我有该属性的自定义属性值,如何获取类的属性名称?当然还有自定义属性名称。

4

1 回答 1

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"
);   
于 2012-05-31T14:24:50.617 回答