Heim >Backend-Entwicklung >C++ >Wie kann ich Strings in C# Enums effizient darstellen?
Eine Methode besteht darin, benutzerdefinierte Attribute und String -Suchmethoden zu verwenden:
<code class="language-csharp">[StringValue("FORMS")] public enum AuthenticationMethod { FORMS = 1, WINDOWSAUTHENTICATION = 2, SINGLESIGNON = 3 } public static class StringEnum { public static string GetStringValue(Enum value) { // 检索 StringValue 属性,如果找到则返回关联的字符串;否则返回 null。 } }</code>Diese Methode erfordert manuelle Anwendungsattribute und wird als relativ lang angesehen.
Eine andere Methode besteht darin, den Typ des sicheren Hubmodus zu berücksichtigen:
<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>Dieses Modell beinhaltet die Erstellung eines Siegels, das dem Aufzug ähnelt, wobei das statische Lesebereich jede Option darstellt. Jedes Feld hat eine String -Repräsentationsform und einen Wert.
Für die Konvertierung des expliziten Typs können Sie den vom Mapping Dictionary und der Benutzerdefinition definierten Typentypkonvertierungsoperator hinzufügen:
<code class="language-csharp">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(); }</code>Diese Methode kombiniert die Vorteile der beiden Methoden: die Art der sicheren und bequemen String -Darstellung und die Typumwandlung der Benutzerdefinition.
Das obige ist der detaillierte Inhalt vonWie kann ich Strings in C# Enums effizient darstellen?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!