嗨,我的工厂代码是这样的。我不想将这些值直接存储在字典中,而是将这些值存储在 app.config 文件中。正如我在下面显示的。
public class HandlerFactory
{
private Dictionary<string, IHandler> _handlers = new Dictionary<string,IHandler>();
public HandlerFactory()
{
_handlers.Add("AMOUNT", new AmountValidator());
_handlers.Add("FLOW", new FlowValidator());
}
public IHandler Create(string key)
{
IHandler result;
_handlers.TryGetValue(key, out result);
return result;
}
}
我会将这些设置移动到我的配置文件中,如下所示。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="Indentifiers" type="System.Configuration.AppSettingsSection"/>
</configSections>
<Indentifiers>
<add key="AMOUNT" value="AmountValidator" />
<add key="FLOW" value="FlowValidator" />
</Indentifiers>
</configuration>
我正在做这样的事情,但我没有成功。不知道如何添加到字典
NameValueCollection settings = ConfigurationManager.GetSection("Indentifiers") as NameValueCollection;
if (settings != null)
{
foreach (string key in settings.AllKeys)
{
_handlers.Add(key.ToString(), settings[key].ToString()); <-- how to handle here
}
}