我有一个枚举类型这样为例:解析字符串枚举类型
public Enum MyEnum {
enum1, enum2, enum3 };
我会读取配置文件中的字符串。我需要它来解析字符串MyEnum类型或null o未定义。不知道下面的代码就可以了(对不起,没有访问我的VS现在):
// example: ParseEnum<MyEnum>("ENUM1", ref eVal);
bool ParseEnum<T>(string value1, ref eVal) where T : Enum
{
bool bRet = false;
var x = from x in Enum.GetNames(typeof(T)) where
string.Equals(value1, x, StringComparison. OrdinalIgnoreCase)
select x;
if (x.Count() == 1)
{
eVal = Enum.Parse(typeof(T), x.Item(0)) as T;
bRet = true;
}
return bRet;
}
不知道是否是正确的或有任何其他简单的方法来解析字符串MyEnum价值?
退房Enum.TryParse,如[此帖](http://www.codeducky.org/ins-提到奏-C-枚举/)。 – ChaseMedallion 2014-07-20 20:25:06