C# type extends interface
I'm currently attempting to read information about an object from the web.config file and create and object based on that. However, I only wish to be able to create objects from classes that extend a particular interface (IModule
). The type of the object is coming from a type attribute in the 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>
In my code, ASPNETMVCMODULES.TestModule
does, in fact, extend IModule
and it loads in just fine with the code below:
Th开发者_开发技巧e problem I am having is that, because I'm defining every object as an IModule
, I cannot gain access to any additional methods or properties I add to the extending class. Is there any way for me to create the object with its own type, whilst ensuring it extends IModule
? Might using System.Convert
be worthwhile to convert from IModule
to TestModule
(in this case)?
Ideally, I'd like to be able to define the object using modT
which is type of the object straight from the 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);
}
}
Thanks
You can determine if a class has a particular interface with the following bit of code:
public void LoadModules()
{
// ...
Type modT = Type.GetType(mod.ModuleType);
if (InheritsFromInterface(modT, typeof(IModule))
{
IModule ob = (IModule)Activator.CreateInstance(modT);
// ...
}
}
public bool InheritsFromInterface(Type inheritor, Type interface)
{
Type result = inheritor.GetInterface(interface.FullName);
return result != null;
}
Hopefully this is what you're after.
You have a few different options, I have used these two myself.
- Use XmlSerializer
- Create an instance with
Activator.CreateInstance(T)
then set the properties yourself using Reflection,PropertyInfo[] props = typeof(T).GetProperties()
and try to find the properties in your created instance.
精彩评论