Reflection - get attribute name and value on property

后端 未结 15 2075
谎友^
谎友^ 2020-11-22 04:59

I have a class, lets call it Book with a property called Name. With that property, I have an attribute associated with it.

public class Book
{
    [Author(\"         


        
15条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 05:13

    I wrote this into a dynamic method since I use lots of attributes throughout my application. Method:

    public static dynamic GetAttribute(Type objectType, string propertyName, Type attrType)
        {
            //get the property
            var property = objectType.GetProperty(propertyName);
    
            //check for object relation
            return property.GetCustomAttributes().FirstOrDefault(x => x.GetType() == attrType);
        }
    

    Usage:

    var objectRelAttr = GetAttribute(typeof(Person), "Country", typeof(ObjectRelationAttribute));
    
    var displayNameAttr = GetAttribute(typeof(Product), "Category", typeof(DisplayNameAttribute));
    

    Hope this helps anyone

提交回复
热议问题