satu kaedah adalah menggunakan atribut tersuai dan kaedah carian rentetan:
[StringValue("FORMS")] public enum AuthenticationMethod { FORMS = 1, WINDOWSAUTHENTICATION = 2, SINGLESIGNON = 3 } public static class StringEnum { public static string GetStringValue(Enum value) { // 检索 StringValue 属性,如果找到则返回关联的字符串;否则返回 null。 } }
Kaedah lain adalah untuk mempertimbangkan jenis mod angkat selamat:
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; } }
Untuk penukaran jenis jenis eksplisit, pertimbangkan untuk menambah pengendali penukaran jenis yang ditakrifkan oleh kamus pemetaan dan definisi pengguna:
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(); }
Atas ialah kandungan terperinci Bagaimanakah saya dapat mewakili rentetan dalam C# enums?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!