C#字符串枚举 [英] C# String enums

查看:420
本文介绍了C#字符串枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下枚举:

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

但是,当我要求AuthenticationMethod.FORMS而不是id 1时,我需要单词FORMS。



我已经找到了这个问题的以下解决方案(链接):



首先,我需要创建一个名为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(枚举值)
{
string output = null;
Type type = value.GetType();

//首先检查我们的缓存结果...

//在字段的自定义属性中查找我们的'StringValueAttribute'

//

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

返回输出;
}
}

现在我有工具来获得枚举器的字符串值。
然后我可以这样使用:

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

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



我还尝试了一些字典和静态属性,但也不是更好。 b $ b

解决方案

尝试 type-安全枚举模式。

  public sealed class AuthenticationMethod {

private readonly String name ;
私有readonly int值;

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>(); 




    • n.b。为了在调用实例构造函数时,枚举成员字段的初始化不会抛出NullReferenceException,请确保将字典字段放在类中的枚举成员字段之前。这是因为静态字段初始化器以声明顺序调用,并且在静态构造函数之前,创建了在所有静态字段已被初始化之前,之前以及调用静态构造函数之前,可以调用实例构造函数的奇怪且必要但令人困惑的情况。 / li>

  • 在实例构造函数中填充此映射

     code> instance [name] = this; 


  • 并添加用户定义的类型转换操作符

      public静态显式运算符AuthenticationMethod(string str)
    {
    AuthenticationMethod result;
    if(instance.TryGetValue(str,out result))
    return result;
    else
    throw new InvalidCastException();
    }



I have the following enumeration:

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

The problem however is that I need the word "FORMS" when I ask for AuthenticationMethod.FORMS and not the id 1.

I have found the following solution for this problem (link):

First I need to create a custom attribute called "StringValue":

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

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

    public string Value
    {
        get { return _value; }
    }

}

Then I can add this attribute to my enumerator:

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

And of course I need something to retrieve that 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;
    }
}

Good now I've got the tools to get a string value for an enumerator. I can then use it like this:

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

Okay now all of these work like a charm but I find it a whole lot of work. I was wondering if there is a better solution for this.

I also tried something with a dictionary and static properties but that wasn't better either.

解决方案

Try type-safe-enum pattern.

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

}


Update Explicit (or implicit) type conversion can be done by

  • adding static field with mapping

    private static readonly Dictionary<string, AuthenticationMethod> instance = new Dictionary<string,AuthenticationMethod>();
    

    • n.b. In order that the initialisation of the the "enum member" fields doesn't throw a NullReferenceException when calling the instance constructor, be sure to put the Dictionary field before the "enum member" fields in your class. This is because static field initialisers are called in declaration order, and before the static constructor, creating the weird and necessary but confusing situation that the instance constructor can be called before all static fields have been initialised, and before the static constructor is called.
  • filling this mapping in instance constructor

    instance[name] = this;
    

  • and adding 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#字符串枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆