Reflection - get attribute name and value on property

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

    Here are some static methods you can use to get the MaxLength, or any other attribute.

    using System;
    using System.Linq;
    using System.Reflection;
    using System.ComponentModel.DataAnnotations;
    using System.Linq.Expressions;
    
    public static class AttributeHelpers {
    
    public static Int32 GetMaxLength(Expression> propertyExpression) {
        return GetPropertyAttributeValue(propertyExpression,attr => attr.Length);
    }
    
    //Optional Extension method
    public static Int32 GetMaxLength(this T instance,Expression> propertyExpression) {
        return GetMaxLength(propertyExpression);
    }
    
    
    //Required generic method to get any property attribute from any class
    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;
    
        if (attr==null) {
            throw new MissingMemberException(typeof(T).Name+"."+propertyInfo.Name,typeof(TAttribute).Name);
        }
    
        return valueSelector(attr);
    }
    
    }
    

    Using the static method...

    var length = AttributeHelpers.GetMaxLength(x => x.PlayerName);
    

    Or using the optional extension method on an instance...

    var player = new Player();
    var length = player.GetMaxLength(x => x.PlayerName);
    

    Or using the full static method for any other attribute (StringLength for example)...

    var length = AttributeHelpers.GetPropertyAttributeValue(prop => prop.PlayerName,attr => attr.MaximumLength);
    

    Inspired by the Mikael Engver's answer.

提交回复
热议问题