Getting attributes of Enum's value

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

    I've merged a couple of the answers here to create a little more extensible solution. I'm providing it just in case it's helpful to anyone else in the future. Original posting here.

    using System;
    using System.ComponentModel;
    
    public static class EnumExtensions {
    
        // This extension method is broken out so you can use a similar pattern with 
        // other MetaData elements in the future. This is your base method for each.
        public static T GetAttribute(this Enum value) where T : Attribute {
            var type = value.GetType();
            var memberInfo = type.GetMember(value.ToString());
            var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false);
            return attributes.Length > 0 
              ? (T)attributes[0]
              : null;
        }
    
        // This method creates a specific call to the above method, requesting the
        // Description MetaData attribute.
        public static string ToName(this Enum value) {
            var attribute = value.GetAttribute();
            return attribute == null ? value.ToString() : attribute.Description;
        }
    
    }
    

    This solution creates a pair of extension methods on Enum. The first allows you to use reflection to retrieve any attribute associated with your value. The second specifically calls retrieves the DescriptionAttribute and returns it's Description value.

    As an example, consider using the DescriptionAttribute attribute from System.ComponentModel

    using System.ComponentModel;
    
    public enum Days {
        [Description("Sunday")]
        Sun,
        [Description("Monday")]
        Mon,
        [Description("Tuesday")]
        Tue,
        [Description("Wednesday")]
        Wed,
        [Description("Thursday")]
        Thu,
        [Description("Friday")]
        Fri,
        [Description("Saturday")]
        Sat
    }
    

    To use the above extension method, you would now simply call the following:

    Console.WriteLine(Days.Mon.ToName());
    

    or

    var day = Days.Mon;
    Console.WriteLine(day.ToName());
    

提交回复
热议问题