One method is to use custom attributes and string search methods:
[StringValue("FORMS")] public enum AuthenticationMethod { FORMS = 1, WINDOWSAUTHENTICATION = 2, SINGLESIGNON = 3 } public static class StringEnum { public static string GetStringValue(Enum value) { // 检索 StringValue 属性,如果找到则返回关联的字符串;否则返回 null。 } }
Another method is to consider the type of safe lift mode:
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; } }
For the conversion of the type of explicit type, consider adding the type conversion operator defined by the mapping dictionary and the user definition:
private static readonly Dictionary<string, AuthenticationMethod> instance = new Dictionary<string, AuthenticationMethod>(); public AuthenticationMethod(int value, string name) { instance[name] = this; } public static explicit operator AuthenticationMethod(string str) { if (instance.TryGetValue(str, out AuthenticationMethod result)) return result; else throw new InvalidCastException(); }
The above is the detailed content of How Can I Efficiently Represent Strings in C# Enums?. For more information, please follow other related articles on the PHP Chinese website!