Reflection - get attribute name and value on property

后端 未结 15 1892
谎友^
谎友^ 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:33

    I have solved similar problems by writing a Generic Extension Property Attribute Helper:

    using System;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Reflection;
    
    public static class AttributeHelper
    {
        public static TValue GetPropertyAttributeValue(
            Expression> propertyExpression, 
            Func valueSelector) 
            where TAttribute : Attribute
        {
            var expression = (MemberExpression) propertyExpression.Body;
            var propertyInfo = (PropertyInfo) expression.Member;
            var attr = propertyInfo.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute;
            return attr != null ? valueSelector(attr) : default(TValue);
        }
    }
    

    Usage:

    var author = AttributeHelper.GetPropertyAttributeValue(prop => prop.Name, attr => attr.Author);
    // author = "AuthorName"
    

提交回复
热议问题