优雅地获取C#枚举的字符串表示
考虑以下枚举:
<code class="language-csharp">public enum AuthenticationMethod { FORMS = 1, WINDOWSAUTHENTICATION = 2, SINGLESIGNON = 3 }</code>
要获取字符串值(例如“FORMS”而不是ID 1),需要自定义解决方案。虽然现有的基于属性的方法和字典方法提供了变通方案,但存在更优雅的解决方案。
类型安全枚举模式
类型安全枚举模式引入一个密封类,将每个枚举成员表示为单独的实例:
<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>
这种模式具有以下优点:
AuthenticationMethod
类确保只使用有效值。显式类型转换
如果需要,可以向AuthenticationMethod
类添加显式类型转换,允许进行字符串到枚举的转换(此部分代码示例中存在问题,需要修正):
<code class="language-csharp">// 修正后的显式类型转换 private static readonly Dictionary<string, AuthenticationMethod> instance = new Dictionary<string, AuthenticationMethod>() { {"FORMS", FORMS}, {"WINDOWS", WINDOWSAUTHENTICATION}, {"SSN", SINGLESIGNON} }; public static explicit operator AuthenticationMethod(string str) { if (instance.TryGetValue(str, out var result)) return result; else throw new InvalidCastException(); }</code>
这允许方便地进行转换,例如:
<code class="language-csharp">AuthenticationMethod method = (AuthenticationMethod)"FORMS";</code>
以上是如何更优雅地获得C#中的枚举的字符串表示?的详细内容。更多信息请关注PHP中文网其他相关文章!