Getting attributes of Enum's value

后端 未结 25 3016
慢半拍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:26

    This piece of code should give you a nice little extension method on any enum that lets you retrieve a generic attribute. I believe it's different to the lambda function above because it's simpler to use and slightly - you only need to pass in the generic type.

    public static class EnumHelper
    {
        /// 
        /// Gets an attribute on an enum field value
        /// 
        /// The type of the attribute you want to retrieve
        /// The enum value
        /// The attribute of type T that exists on the enum value
        /// ().Description;]]>
        public static T GetAttributeOfType(this Enum enumVal) where T:System.Attribute
        {
            var type = enumVal.GetType();
            var memInfo = type.GetMember(enumVal.ToString());
            var attributes = memInfo[0].GetCustomAttributes(typeof(T), false);
            return (attributes.Length > 0) ? (T)attributes[0] : null;
        }
    }
    

提交回复
热议问题