Getting attributes of Enum's value

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

    Here is code to get information from a Display attribute. It uses a generic method to retrieve the attribute. If the attribute is not found it converts the enum value to a string with pascal/camel case converted to title case (code obtained here)

    public static class EnumHelper
    {
        // Get the Name value of the Display attribute if the   
        // enum has one, otherwise use the value converted to title case.  
        public static string GetDisplayName(this TEnum value)
            where TEnum : struct, IConvertible
        {
            var attr = value.GetAttributeOfType();
            return attr == null ? value.ToString().ToSpacedTitleCase() : attr.Name;
        }
    
        // Get the ShortName value of the Display attribute if the   
        // enum has one, otherwise use the value converted to title case.  
        public static string GetDisplayShortName(this TEnum value)
            where TEnum : struct, IConvertible
        {
            var attr = value.GetAttributeOfType();
            return attr == null ? value.ToString().ToSpacedTitleCase() : attr.ShortName;
        }
    
        /// 
        /// Gets an attribute on an enum field value
        /// 
        /// The enum type
        /// The type of the attribute you want to retrieve
        /// The enum value
        /// The attribute of type T that exists on the enum value
        private static T GetAttributeOfType(this TEnum value)
            where TEnum : struct, IConvertible
            where T : Attribute
        {
    
            return value.GetType()
                        .GetMember(value.ToString())
                        .First()
                        .GetCustomAttributes(false)
                        .OfType()
                        .LastOrDefault();
        }
    }
    

    And this is the extension method for strings for converting to title case:

        /// 
        /// Converts camel case or pascal case to separate words with title case
        /// 
        /// 
        /// 
        public static string ToSpacedTitleCase(this string s)
        {
            //https://stackoverflow.com/a/155486/150342
            CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
            TextInfo textInfo = cultureInfo.TextInfo;
            return textInfo
               .ToTitleCase(Regex.Replace(s, 
                            "([a-z](?=[A-Z0-9])|[A-Z](?=[A-Z][a-z]))", "$1 "));
        }
    

提交回复
热议问题