且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#字符串的枚举

更新时间:2022-03-06 03:02:21

尝试类型安全,枚举模式

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。为了在调用构造函数时的枚举成员字段的初始化没有抛出一个NullReferenceException,一定要把字典前场在你的类中的枚举成员字段。这是因为静态字段initialisers被称为声明顺序和静态构造函数之前,创建怪异的和必要的,但混乱的局面,所有的静态字段都被初始化前的实例构造函数可以调用,静态构造函数被调用之前。

  • 在实例构造填补这一映射

    filling this mapping in instance constructor

instance[name] = this;


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

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