The previous scheme uses custom attributes to retrieve enumeration string representation. Although the function is valid, it may look lengthy. The following is an alternative method to use type secure enumeration mode:
This model defines the explicit instance of enumeration, which contains string and value representation.
<code class="language-csharp">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; } }</code>
ToString()
Different type conversion
In order to enable the explicit type conversion, you can add a static member for mapping to the class:
Fill in the dictionary in the constructor of the class:
<code class="language-csharp">private static readonly Dictionary<string, AuthenticationMethod> instance = new Dictionary<string, AuthenticationMethod>();</code>
Finally, add a user -defined type conversion operator:
<code class="language-csharp">instance[name] = this;</code>
This allows you to explicitly convert the string to
instance to make the type conversion process more direct.<code class="language-csharp">public static explicit operator AuthenticationMethod(string str) { AuthenticationMethod result; if (instance.TryGetValue(str, out result)) return result; else throw new InvalidCastException(); }</code>
The above is the detailed content of How Can We Improve String Representation of Enumerations Using Type-Safe Enums and Explicit Type Conversion?. For more information, please follow other related articles on the PHP Chinese website!