开发者

Reflection usage for creating instance of a class into DLL

开发者 https://www.devze.com 2023-01-28 00:27 出处:网络
I have the following code: var type = typeof(PluginInterface.iMBDDXPluginInterface); var types = AppDomain.CurrentDomain.GetAssemblies().ToList()

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 .

0

精彩评论

暂无评论...
验证码 换一张
取 消