Get the string of C#enumerated elegantly
Consider the following enumeration:
To get string values (such as "Forms" instead of ID 1), a solution is required. Although the existing attribute -based methods and dictionary methods provides a transformation solution, there are more elegant solutions.
public enum AuthenticationMethod { FORMS = 1, WINDOWSAUTHENTICATION = 2, SINGLESIGNON = 3 }
<型> Type safe enumeration mode
Type safe enumeration mode introduces a sealing class, and each enumeration member is expressed as a separate example:
This model has the following advantages:
public sealed class AuthenticationMethod { private readonly string name; private readonly int value; public static readonly AuthenticationMethod FORMS = new AuthenticationMethod(1, "FORMS"); public static readonly AuthenticationMethod WINDOWSAUTHENTICATION = new AuthenticationMethod(2, "WINDOWS"); public static readonly AuthenticationMethod SINGLESIGNON = new AuthenticationMethod(3, "SSN"); private AuthenticationMethod(int value, string name) { this.name = name; this.value = value; } public override string ToString() { return name; } }
Type safety:
AuthenticationMethod
This allows easy conversion, for example:
The above is the detailed content of How Can I Get the String Representation of an Enum in C# More Elegantly?. For more information, please follow other related articles on the PHP Chinese website!