简体   繁体   中英

Get property name by attribute value

Good day, How can I get class's property name, if I have custom attribute value for that property? and custom attribute name of course.

Get property name by custom attribute:

    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();
      }
    }

Test fixtures:

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;
    }
  }

}

Test cases:

// 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"
);   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM