Using reflection to instantiate a class in a 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 inside the dll implements PluginInterface and Type in the code above, is certainly the correct class / type, however, when I try to create an instance through the interface, I get an error message:

A reference to an object that is not tied to an instance of the object.

Does anyone know why?

Thank.

+3
source share
2 answers

Anyway

TabPage tp = new TabPage();
tp = instance.pluginTabPage();

doesn't make sense.

do:

TabPage tp = instance.pluginTabPage();

Also follow these steps:

Type type = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(s => s.GetTypes())
    .FirstOrDefault(p => type.IsAssignableFrom(p));
if (type != null)
{
    // create instance
}

or (my preferred method):

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);
+3
source

Try to see the type of reflector. Maybe the constructor accepts the arguments that you're skipping wrong Activator.CreateInstance.

+1

Source: https://habr.com/ru/post/1777911/


All Articles