Une méthode consiste à utiliser des attributs personnalisés et des méthodes de recherche de chaîne:
[StringValue("FORMS")] public enum AuthenticationMethod { FORMS = 1, WINDOWSAUTHENTICATION = 2, SINGLESIGNON = 3 } public static class StringEnum { public static string GetStringValue(Enum value) { // 检索 StringValue 属性,如果找到则返回关联的字符串;否则返回 null。 } }
Une autre méthode consiste à considérer le type de mode de levage sûr:
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; } }
Pour la conversion du type de type explicite, envisagez d'ajouter l'opérateur de conversion de type défini par le dictionnaire de mappage et la définition de l'utilisateur:
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(); }
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!