String representation of an Enum

后端 未结 30 1955
不思量自难忘°
不思量自难忘° 2020-11-22 02:44

I have the following enumeration:

public enum AuthenticationMethod
{
    FORMS = 1,
    WINDOWSAUTHENTICATION = 2,
    SINGLESIGNON = 3
}

T

30条回答
  •  逝去的感伤
    2020-11-22 03:11

    I use the Description attribute from the System.ComponentModel namespace. Simply decorate the enum and then use this code to retrieve it:

    public static string GetDescription(this object enumerationValue)
                where T : struct
            {
                Type type = enumerationValue.GetType();
                if (!type.IsEnum)
                {
                    throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
                }
    
                //Tries to find a DescriptionAttribute for a potential friendly name
                //for the enum
                MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
                if (memberInfo != null && memberInfo.Length > 0)
                {
                    object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
    
                    if (attrs != null && attrs.Length > 0)
                    {
                        //Pull out the description value
                        return ((DescriptionAttribute)attrs[0]).Description;
                    }
                }
                //If we have no description attribute, just return the ToString of the enum
                return enumerationValue.ToString();
    
            }
    

    As an example:

    public enum Cycle : int
    {        
       [Description("Daily Cycle")]
       Daily = 1,
       Weekly,
       Monthly
    }
    

    This code nicely caters for enums where you don't need a "Friendly name" and will return just the .ToString() of the enum.

提交回复
热议问题