尝试使用类型安全的枚举模式。
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;
并添加用户定义的类型转换运算符
public static explicit operator AuthenticationMethod(string str)
{
AuthenticationMethod result;
if (instance.TryGetValue(str, out result))
return result;
else
throw new InvalidCastException();
}



