Reflection - get attribute name and value on property

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

    While the above most upvoted answers definitely work, I'd suggest using a slightly different approach in some cases.

    If your class has multiple properties with always the same attribute and you want to get those attributes sorted into a dictionary, here is how:

    var dict = typeof(Book).GetProperties().ToDictionary(p => p.Name, p => p.GetCustomAttributes(typeof(AuthorName), false).Select(a => (AuthorName)a).FirstOrDefault());
    

    This still uses cast but ensures that the cast will always work as you will only get the custom attributes of the type "AuthorName". If you had multiple Attributes above answers would get a cast exception.

    0 讨论(0)
  • 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<T, TOut, TAttribute, TValue>(
            Expression<Func<T, TOut>> propertyExpression, 
            Func<TAttribute, TValue> 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<Book, string, AuthorAttribute, string>(prop => prop.Name, attr => attr.Author);
    // author = "AuthorName"
    
    0 讨论(0)
  • 2020-11-22 05:36
    foreach (var p in model.GetType().GetProperties())
    {
       var valueOfDisplay = 
           p.GetCustomAttributesData()
            .Any(a => a.AttributeType.Name == "DisplayNameAttribute") ? 
                p.GetCustomAttribute<DisplayNameAttribute>().DisplayName : 
                p.Name;
    }
    

    In this example I used DisplayName instead of Author because it has a field named 'DisplayName' to be shown with a value.

    0 讨论(0)
提交回复
热议问题