dll - Load a class dynamically in C# -
i trying load class (say class1:interface ) without knowing name assembly. code looks this:
assembly = assembly.loadfrom("mydll.dll"); type t = (type)a.gettypes()[0]; (interface) classinstance = (interface) (clasactivator.createinstance(t);
based on articles found online , msdn, gettypes()[0]
suppose return class1 (there 1 class in mydll.dll). however, code returns class1.properties.settings
. line 3 creates exception:
unable cast object of type 'class1.properties.settings' type namespace.interface'.
i not know why , how fix problem.
the assembly can hold more 1 type (you have settings.settings
file in dll, creates class under hood in settings.designer.cs
file), first class in code in case turned out settings
class, need go through types , search ones have interface need.
assembly asm = assembly.loadfrom("mydll.dll"); type[] alltypes = asm.gettypes(); foreach (type type in alltypes) { // scan objects not abstract , implements interface if (!type.isabstract && typeof(imyinterface).isassignablefrom(type)); { // create instance of class... var inst = (imyinterface)activator.createinstance(type); //do work here, may called more once if more 1 class implements imyinterface } }
Comments
Post a Comment