String representation of an Enum

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

    In your question you never said that you actually need the numeric value of the enum anywhere.

    If you do not and just need an enum of type string (which is not an integral type so can not be a base of enum) here is a way:

        static class AuthenticationMethod
        {
            public static readonly string
                FORMS = "Forms",
                WINDOWSAUTHENTICATION = "WindowsAuthentication";
        }
    

    you can use the same syntax as enum to reference it

    if (bla == AuthenticationMethod.FORMS)
    

    It will be a bit slower than with numeric values (comparing strings instead of numbers) but on the plus side it is not using reflection (slow) to access the string.

提交回复
热议问题