Possible Duplicate:
Cast a String to an Enum Tag in C#
How to convert a string which have a name of existing enum-TAG (have name of Enum Title) to become of type of Enum
Not to become one of the Enum listed variables values,
But to be the Enum-Tag name which is of type Enum?For instance, I might have
Enum MyEnum { A,B,C,D };
and then
String a = "MyEnum";
You need to parse it as Enum using Enum.Parse:
myEnum result = (myEnum)Enum.Parse(typeof(myEnum), stringToConvert);
There is a couple of elements to consider here. First of all the Enum.Parse takes the type of the target Enum. Second is it only returns type object so you need to manually convert it to the correct enum type.
MyEnum value = (MyEnum)Enum.Parse(typeof(MyEnum), "myname");
Enum e = (Enum)Enum.Parse(typeof(Enum), "A", true);
this should do it
精彩评论