开发者

How to Cast string to be the Enum-Tag value in C# ( to be The Enum Name )? [duplicate]

开发者 https://www.devze.com 2023-02-06 04:51 出处:网络
This question already has answers here: 开发者_StackOverflow社区 Closed 12 years ago. Possible Duplicate:
This question already has answers here: 开发者_StackOverflow社区 Closed 12 years ago.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号