c# - 枚举的字符串表示

标签 c# enums

我有以下枚举:

public enum AuthenticationMethod
{
    FORMS = 1,
    WINDOWSAUTHENTICATION = 2,
    SINGLESIGNON = 3
}

但是问题是,当我请求 AuthenticationMethod.FORMS 而不是 id 1 时,我需要“FORMS”这个词。

我找到了解决此问题的以下方法 ( link ):

首先我需要创建一个名为“StringValue”的自定义属性:

public class StringValue : System.Attribute
{
    private readonly string _value;

    public StringValue(string value)
    {
        _value = value;
    }

    public string Value
    {
        get { return _value; }
    }

}

然后我可以将此属性添加到我的枚举器中:

public enum AuthenticationMethod
{
    [StringValue("FORMS")]
    FORMS = 1,
    [StringValue("WINDOWS")]
    WINDOWSAUTHENTICATION = 2,
    [StringValue("SSO")]
    SINGLESIGNON = 3
}

当然,我需要一些东西来检索那个 StringValue:

public static class StringEnum
{
    public static string GetStringValue(Enum value)
    {
        string output = null;
        Type type = value.GetType();

        //Check first in our cached results...

        //Look for our 'StringValueAttribute' 

        //in the field's custom attributes

        FieldInfo fi = type.GetField(value.ToString());
        StringValue[] attrs =
           fi.GetCustomAttributes(typeof(StringValue),
                                   false) as StringValue[];
        if (attrs.Length > 0)
        {
            output = attrs[0].Value;
        }

        return output;
    }
}

很好,现在我有了获取枚举器字符串值的工具。 然后我可以像这样使用它:

string valueOfAuthenticationMethod = StringEnum.GetStringValue(AuthenticationMethod.FORMS);

好吧,现在所有这些都像魅力一样工作,但我发现它需要大量工作。我想知道是否有更好的解决方案。

我还尝试了一些带有字典和静态属性的东西,但这也不是更好。

最佳答案

尝试 type-safe-enum模式。

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;
    }

}

更新 显式(或隐式)类型转换可以通过

  • 使用映射添加静态字段

    private static readonly Dictionary<string, AuthenticationMethod> instance = new Dictionary<string,AuthenticationMethod>();
    
    • 注意为了在调用实例构造函数时“枚举成员”字段的初始化不会抛出 NullReferenceException,请确保将 Dictionary 字段放在类中“枚举成员”字段之前。这是因为静态字段初始化器是按声明顺序调用的,并且在静态构造函数之前,这造成了一种奇怪且必要但令人困惑的情况,即可以在初始化所有静态字段之前以及调用静态构造函数之前调用实例构造函数。
  • 在实例构造函数中填充此映射

    instance[name] = this;
    
  • 并添加 user-defined type conversion operator

    public static explicit operator AuthenticationMethod(string str)
    {
        AuthenticationMethod result;
        if (instance.TryGetValue(str, out result))
            return result;
        else
            throw new InvalidCastException();
    }
    

关于c# - 枚举的字符串表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/424366/

相关文章:

ios - Swift 中枚举的默认值

c - 避免与 C (C99) 中的枚举发生名称冲突

c++ - 无法访问嵌套私有(private)枚举的枚举数

c# - 增强我的代码的指南

c# - 根据背景颜色更改按钮的鼠标悬停颜色

typescript - 使用枚举作为类型允许枚举中不存在的值

c++11 - C++ 11 如何通过int值获取枚举类值?

c# - 使用 C# Linq 将对象插入到列表中

c# - 如何限定一个类只能在类库项目中使用?

C# 通用类型事件参数