문제

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