Getting attributes of Enum's value

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

    If your enum contains a value like Equals you might bump into a few bugs using some extensions in a lot of answers here. This is because it is normally assumed that typeof(YourEnum).GetMember(YourEnum.Value) would return only one value, which is the MemberInfo of your enum. Here's a slightly safer version Adam Crawford's answer.

    public static class AttributeExtensions
    {
        #region Methods
    
        public static T GetAttribute(this Enum enumValue) where T : Attribute
        {
            var type = enumValue.GetType();
            var memberInfo = type.GetMember(enumValue.ToString());
            var member = memberInfo.FirstOrDefault(m => m.DeclaringType == type);
            var attribute = Attribute.GetCustomAttribute(member, typeof(T), false);
            return attribute is T ? (T)attribute : null;
        }
    
        #endregion
    }
    

提交回复
热议问题