所以我有一个字符串,我想从枚举中获取一个值以返回与字符串相同的名称。例子:
enum Types{
one,
two,
three
}
private Types getType(string value){ //Let's say value is "two"
return Types.value; //This should return the enum "two" of Types
}
我希望我说得足够清楚!
使用 Enum.Parse
var t = (Types)Enum.Parse(typeof(Types), "two");
如果您使用的是 .NET 4.0 或更高版本,则可以使用Enum.TryParse<TEnum> 方法:
Types result;
if (Enum.TryParse<Types>("two", out result))
{
// result == Types.two
}