【发布时间】:2010-06-21 10:20:07
【问题描述】:
我目前正在尝试从 web.config 文件中读取有关对象的信息,并基于此创建对象。但是,我只希望能够从扩展特定接口 (IModule) 的类中创建对象。对象的类型来自 web.config 中的类型属性:
<module moduleAlias="Test" type="ASPNETMVCMODULES.TestModule" connectionStringName="ApplicationServices">
<properties>
<property name="prop1" value="abc" type="System.String"/>
<property name="prop2" value="123" type="System.Int32"/>
</properties>
</module>
在我的代码中,ASPNETMVCMODULES.TestModule 实际上扩展了IModule,它可以通过以下代码正常加载:
我遇到的问题是,因为我将每个对象都定义为IModule,所以我无法访问我添加到扩展类的任何其他方法或属性。我有什么方法可以创建具有自己类型的对象,同时确保它扩展IModule?使用System.Convert 是否值得将IModule 转换为TestModule(在这种情况下)?
理想情况下,我希望能够使用modT 定义对象,这是直接来自 web.config 的对象类型。
public void LoadModules()
{
ASPNETMVCMODULES.Configuration.ModulesSection allModules = (ASPNETMVCMODULES.Configuration.ModulesSection)System.Web.Configuration.WebConfigurationManager.GetSection("mvcmodules");
foreach (Configuration.Module mod in allModules.Modules)
{
Type modT = Type.GetType(mod.ModuleType);
IModule ob = (IModule)Activator.CreateInstance(modT);
foreach (ASPNETMVCMODULES.Configuration.ModuleProperty modP in mod.ModuleProperties)
{
object origVal = modP.Value;
object newVal = Convert.ChangeType(origVal, Type.GetType(modP.PropertyTypeString));
ob.Properties.Add(modP.Name, newVal);
}
//Have to add some properties manually
ob.Properties.Add("ConnectionString", (string)mod.ConnectionString);
//RegisterModule(string, IModule)
RegisterModule(mod.ModuleAlias, ob);
}
}
谢谢
【问题讨论】: