我有一个配置文件,其中包含:
<add key="x36_key1" value="D1"/>
<add key="x36_key2" value="D2"/>
<add key="x36_key3" value="D3"/>
<add key="x36_key4" value="D4"/>
<add key="x36_key5" value="D5"/>
现在我需要在这里使用这些键:
case Keys.D1:
//something happens here
break;
case Keys.D2:
//something happens here
break;
case Keys.D3:
//something happens here
break;
case Keys.D4:
//something happens here
break;
case Keys.D5:
//something happens here
break;
我从每个键中提取值的方式如下:
string key1 = System.Configuration.ConfigurationManager.AppSettings["x36_key1"];
但由于它是一个字符串,因此无法用作密钥。
如何让代码读取配置文件中定义的键?
答案 0 :(得分:3)
您应该将字符串解析为枚举Keys
(msdn):
string key1 = System.Configuration.ConfigurationManager.AppSettings["x36_key1"];
Keys key;
if (Enum.TryParse<Keys>(key1, out key))
{
switch (key)
{
case Keys.D1:
//something happens here
break;
case Keys.D2:
//something happens here
break;
case Keys.D3:
//something happens here
break;
case Keys.D4:
//something happens here
break;
case Keys.D5:
//something happens here
break;
}
}
答案 1 :(得分:0)
<强>更新强>
将配置中的字符串解析为Keys
枚举
var keyFromConfiguration = System.Configuration.ConfigurationManager.AppSettings["x36_key1"];
Keys key = (Keys) Enum.Parse(typeof(Keys), keyFromConfiguration);
switch (key)
{
case Keys.D1:
//something happens here
break;
case Keys.D2:
//something happens here
break;
case Keys.D3:
//something happens here
break;
case Keys.D4:
//something happens here
break;
case Keys.D5:
//something happens here
break;
}
答案 2 :(得分:0)
string key1 = System.Configuration.ConfigurationManager.AppSettings["x36_key1"];
Keys k1 = (Keys)Enum.Parse(typeof(Keys), key1);