String representation of an Enum

后端 未结 30 2310
不思量自难忘°
不思量自难忘° 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:18

    How I solved this as an extension method:

    using System.ComponentModel;
    public static string GetDescription(this Enum value)
    {
        var descriptionAttribute = (DescriptionAttribute)value.GetType()
            .GetField(value.ToString())
            .GetCustomAttributes(false)
            .Where(a => a is DescriptionAttribute)
            .FirstOrDefault();
    
        return descriptionAttribute != null ? descriptionAttribute.Description : value.ToString();
    }
    

    Enum:

    public enum OrderType
    {
        None = 0,
        [Description("New Card")]
        NewCard = 1,
        [Description("Reload")]
        Refill = 2
    }
    

    Usage (where o.OrderType is a property with the same name as the enum):

    o.OrderType.GetDescription()
    

    Which gives me a string of "New Card" or "Reload" instead of the actual enum value NewCard and Refill.

提交回复
热议问题