String representation of an Enum

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

I have the following enumeration:

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

T

30条回答
  •  梦毁少年i
    2020-11-22 03:14

    I use an extension method:

    public static class AttributesHelperExtension
        {
            public static string ToDescription(this Enum value)
            {
                var da = (DescriptionAttribute[])(value.GetType().GetField(value.ToString())).GetCustomAttributes(typeof(DescriptionAttribute), false);
                return da.Length > 0 ? da[0].Description : value.ToString();
            }
    }
    

    Now decorate the enum with:

    public enum AuthenticationMethod
    {
        [Description("FORMS")]
        FORMS = 1,
        [Description("WINDOWSAUTHENTICATION")]
        WINDOWSAUTHENTICATION = 2,
        [Description("SINGLESIGNON ")]
        SINGLESIGNON = 3
    }
    

    When you call

    AuthenticationMethod.FORMS.ToDescription() you will get "FORMS".

提交回复
热议问题