1つの方法は、カスタム属性と文字列検索方法を使用することです。
この方法には手動アプリケーション属性が必要であり、比較的長いと見なされます。
<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>
別の方法は、セーフリフトモードのタイプを考慮することです。
このモデルには、リフトに似たシールを作成することが含まれます。ここでは、静的読み取りフィールドが各オプションを表します。各フィールドには、文字列表現フォームと値があります。
<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>明示的なタイプのタイプの変換については、マッピング辞書とユーザー定義で定義されたタイプ変換演算子を追加することを検討してください。
このメソッドは、2つの方法の利点を組み合わせています。安全で便利な文字列表現のタイプと、ユーザー定義のタイプ変換です。
以上がC#enumsで文字列を効率的に表現するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。