Reflection usage for creating instance of a class into DLL
I have the following code:
var type = typeof(PluginInterface.iMBDDXPluginInterface);
var types = AppDomain.CurrentDomain.GetAssemblies().ToList()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));
Type t = types.ElementAt(0);
PluginInterface.iMBDDXPluginInterface instance = Activator.CreateInstance(t) as PluginInterface.iMBDDXPluginInterface;
TabPage tp = new TabPage();
tp = instance.pluginTabPage();
The class within the dll implements the PluginInterface and the Type in the code above, is definately the correct class/type, however when I try to create an instance through the interface i get an error message saying:
Object reference not assigned to an 开发者_如何学Cinstance of an object.
Anybody know why?
Thanks.
Anyway
TabPage tp = new TabPage();
tp = instance.pluginTabPage();
makes no sense.
Do:
TabPage tp = instance.pluginTabPage();
Also do next:
Type type = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.FirstOrDefault(p => type.IsAssignableFrom(p));
if (type != null)
{
// create instance
}
or (my preferred way):
from asm in AppDomain.CurrentDomain.GetAssemblies()
from type in asm.GetTypes()
where !type.IsInterface && !type.IsAbstract && typeof(ITarget).IsAssignableFrom(type)
select (ITarget)Activator.CreateInstance(type);
Try looking at the type in reflector. Maybe the constructor takes arguments that you are not correctly passing to Activator.CreateInstance
.
精彩评论