I have a function that gets two strings - a key and a value. I need to parse the value from string to enum. the key represent which enum I need to use. I wanted to use "if"s -

if (keyString == "e1")
{
    (MyEnum1)Enum.Parse(typeof(MyEnum1), valueString, true);
} 
else if (keyString == "e2") 
{
    (MyEnum2)Enum.Parse(typeof(MyEnum2), valueString, true);
} 
else if .....

But then I thought maybe I can create a dictionary of key and enum -

<"e1", MyEnum1>, 

<"e2", MyEnum2>,

...

and then use the dictionary's values for the enum parsing

    (dic[keyString])Enum.Parse(typeof(dic[keyString]), valueString, true)

but I couldn't do it..

I there any other way?

有帮助吗?

解决方案

Just store the type directly in the dictionary (i.e. store the result of typeof(MyEnum1)):

Dictionary<string, Type> KeyToEnum = new Dictionary<string, Type>();

KeyToEnum["e1"] = typeof(MyEnum1);
KeyToEnum["e2"] = typeof(MyEnum2);

Object EnumValue = Enum.Parse(dic[keyString), valueString, true);
// Note that EnumValue is an object, because we can't know at compile time what the type will be.

Note that if instead of "e1", "e2"... you actually had "MyEnum1", "MyEnum2" (i.e. the actual name of the type you could do Type.GetType(MyKey) instead of the dictionary.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top