String representation of an Enum

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

    Here is yet another way to accomplish the task of associating strings with enums:

    struct DATABASE {
        public enum enums {NOTCONNECTED, CONNECTED, ERROR}
        static List strings =
            new List() {"Not Connected", "Connected", "Error"};
    
        public string GetString(DATABASE.enums value) {
            return strings[(int)value];
        }
    }
    

    This method is called like this:

    public FormMain() {
        DATABASE dbEnum;
    
        string enumName = dbEnum.GetString(DATABASE.enums.NOTCONNECTED);
    }
    

    You can group related enums in their own struct. Since this method uses the enum type, you can use Intellisense to display the list of enums when making the GetString() call.

    You can optionally use the new operator on the DATABASE struct. Not using it means the strings List is not allocated until the first GetString() call is made.

提交回复
热议问题