简体   繁体   English

C#-类字典

[英]C# - Dictionary of classes

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 (ie store the result of typeof(MyEnum1) ): 只需将类型直接存储在字典中即可(即存储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" (ie the actual name of the type you could do Type.GetType(MyKey) instead of the dictionary. 请注意,如果实际上不是“ e1”,“ e2” ...而是“ MyEnum1”,“ MyEnum2”(即类型的实际名称,则可以使用Type.GetType(MyKey)代替字典。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM