. NET is often used to dynamically load DLLs, and DLLs may contain various parameters, methods, forms, how to invoke the dynamic loading of these parameters, methods, forms?
In C #, we want to use reflection, first to understand the relationships of several classes in the following namespaces:
System.Reflection namespaces
(1) AppDomain: An application domain that can be understood as a logical container for a set of assemblies
(2) Assembly: assembly class
(3) Module: Modular class
(4) Type: The most core class for using reflection to get type information
There is a dependency between them, that is, an AppDomain can contain N assembly, a assembly can contain n module, and a module can contain n type.
In the program, if we want to dynamically load an assembly there are several ways to use it, namely load, LoadFrom, LoadFile, LoadWithPartialName methods.
The difference between the following assembly.loadfile and Assembly.LoadFrom is emphatically explained.
1, assembly.loadfile only load the corresponding DLL file, such as Assembly.loadfile ("Abc.dll"), then load Abc.dll, if Abc.dll is referenced def.dll, Def.dll will not be loaded.
Assembly.LoadFrom is not the same, it loads the DLL file and other DLLs it references, such as the example above, Def.dll will also be loaded.
2, when loading a assembly with Assembly.LoadFrom, will first check whether the front has been loaded with the same name assembly, such as Abc.dll has two versions (version 1 under directory 1, version 2 is placed under directory 2), the program was initially loaded in version 1, When loading version 2 o'clock with Assembly.LoadFrom ("2\\abc.dll"), it cannot be loaded, but instead returns version 1. Assembly.loadfile will not do such a check, such as the above example to Assembly.loadfile, then the correct loading version 2.
LoadFile: Loads the contents of the assembly file on the specified path. LoadFrom: Loads the contents of the assembly file based on the file name of the assembly.
Finally, the calling method
Assembly outerAsm = Assembly.LoadFrom(@"urPath\MyDLL.dll");
Calling methods in a DLL class
Type type = Outerasm. GetType ("Mydll.myclass");//invocation type
MethodInfo method = Type. GetMethod ("myvoid");//Call method
If you need to pass parameters
object[] paramertors = new object[] {"3087", "2005"};//parameter Collection
Object Test = method. Invoke (null, paramertors);//invoke Call method
Calling a form in a DLL
Type outerForm = outerAsm.GetType(
"MyForm"
,
false
);//找到指定窗口
(Activator.CreateInstance(outerForm)
as
Form).Show();//转换成窗体类,显示
C #, dynamically loading DLLs, by reflection, calling parameters, methods, forms