Return Enum Constant based on an incoming String Value
I'm going to grab the enum value from a querystring.
For instance lets say I have this enum:
Enum MyEnum
{
Test1,
Test2,
Test3
}
I'm going to grab the value from an incoming querystring, so:
string myEnumStringValue = Request["somevar"];
myEnumStringValue could be "0", "1", "2"
I need to get back the actual Enum Constant 开发者_运维知识库based on that string value.
I could go and create a method that takes in the string and then perform a case statement
case "0":
return MyEnum.Test1;
break;
but there's got to be an easier or more slick way to do this?
Take a look at Enum.Parse
, which can convert names or values to the correct enum value.
Once you have that, cast the result to MyEnum
and call ToString()
to get the name of the constant.
return ((MyEnum)Enum.Parse(typeof(MyEnum), Request["somevar"])).ToString();
There is built-in functionality for this task:
MyEnum convertedEnum = (MyEnum) Enum.Parse(typeof(MyEnum), myEnumStringValue);
You need to parse the string to get its integer value, cast the value to the Enum
type, then get the enum value's name, like this:
string myEnumStringValue = ((MyEnum)int.Parse(Request["somevar"])).ToString();
EDIT: Or, you can simply call Enum.Parse
. However, this should be a little bit faster.
精彩评论