String representation of an Enum

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

    I agree with Keith, but I can't vote up (yet).

    I use a static method and swith statement to return exactly what I want. In the database I store tinyint and my code only uses the actual enum, so the strings are for UI requirements. After numerous testing this resulted in the best performance and most control over the output.

    public static string ToSimpleString(this enum)
    {
         switch (enum)
         {
             case ComplexForms:
                 return "ComplexForms";
                 break;
         }
    }
    
    public static string ToFormattedString(this enum)
    {
         switch (enum)
         {
             case ComplexForms:
                 return "Complex Forms";
                 break;
         }
    }
    

    However, by some accounts, this leads to a possible maintenance nightmare and some code smell. I try to keep an eye for enums that are long and a lot of enums, or those that change frequently. Otherwise, this has been a great solution for me.

提交回复
热议问题