【发布时间】:2012-07-27 18:59:21
【问题描述】:
您好,我的工厂代码是这样的。我不想将这些值直接存储在字典中,而是将这些值存储在 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
}
}
【问题讨论】:
-
Activator.CreateInstance在这里应该很有用。 -
嗨混沌,我在我的主类而不是工厂类中调用 createInstance。在我的主课中,我正在做这样的事情' IHandler validator = handle.Create(arInfo[0].ToString()); IHandler handler = (IHandler)Activator.CreateInstance("Validation", validator.ToString()).Unwrap();'但我不明白如何将键的值转换为 IHandler 类型。 IE。在我的工厂类中从“AmountValidator”到“Ihandler 类型的 AmountValidator”。你明白我的意思吗?可以请教吗?
-
我认为您不了解工厂的目的。考虑一下定义。汽车厂会生产汽车的蓝图还是实际的汽车?
标签: c# configuration dictionary abstract-factory