Getting attributes of Enum's value

后端 未结 25 2580
慢半拍i
慢半拍i 2020-11-22 00:35

I would like to know if it is possible to get attributes of the enum values and not of the enum itself? For example, suppose I have the following <

25条回答
  •  一生所求
    2020-11-22 01:27

    This is a generic implementation using a lambda for the selection

    public static Expected GetAttributeValue(this Enum enumeration, Func expression)
        where T : Attribute
    {
        T attribute =
          enumeration
            .GetType()
            .GetMember(enumeration.ToString())
            .Where(member => member.MemberType == MemberTypes.Field)
            .FirstOrDefault()
            .GetCustomAttributes(typeof(T), false)
            .Cast()
            .SingleOrDefault();
    
        if (attribute == null)
            return default(Expected);
    
        return expression(attribute);
    }
    

    Call it like this:

    string description = targetLevel.GetAttributeValue(x => x.Description);
    

提交回复
热议问题