The principle is as follows:
1. Dynamic loading and invocation using reflection.
Assembly Ass=assembly.loadfrom (DllPath); Use the DLL's path to load and load the assembly on which the Assembly depends, with the suffix. dll
Assembly.loadfile loads only the specified files and does not automatically load dependent assemblies. Assmbly.load no post-suffix name
2 . After loading the DLL, you need to use a class in the DLL.
Type Type=ass. GetType ("TypeName");// Get type with namespace and name of type
3, need to instantiate the type, can be used, parameters can be artificially specified, can also have no parameters, static instances can be omitted
Object obj =activator.createinstance (type,params[]);// using the specified argument instance session type
4.call a method in the type:
Note: If you are a static method of a class, you can call it directly, such as string strreturn = (string) type. InvokeMember ("Getnewvalue", bindingflags.declaredonly| bindingflags.public| bindingflags.static| Bindingflags.invokemethod,null, NULL, new object[]{);
Need to get this method first
MethodInfo Mi=type. GetMethod ("Mehtodname");//method name obtained by method
5, then call the method, polymorphism using parameters to control
Oil Invoke (obj,params[]);// based on the parameter line method, The return value is the return value of the original method
#regionDeclaring parameters that dynamically load DLLsObjectobj=NULL; byte[] filesbyte; Assembly Assembly; Type type; MethodInfo timerinitial; MethodInfo Timerdispose;#endregion Private voidLoaddll ()//Load DLL { Try{filesbyte=file.readallbytes (Path.getdirectoryname (Application.executablepath) +"\\loadDll.dll"); Assembly=Assembly.Load (Filesbyte); Type=assembly. GetType ("Test.loaddll"); Obj=System.Activator.CreateInstance (type); Timerstart=TP. GetMethod ("Timerstart"); Timerstop=TP. GetMethod ("Timerstop"); if(Timerstart! =NULL) {Timerstart.invoke (obj,NULL); } } Catch(Exception) {}}
The following excerpt from MSDN
Public classa{ Public Virtual intMethod () {return 0;}} Public classb{ Public Virtual intMethod () {return 1;}}classmymethodinfo{ Public Static intMain () {Console.WriteLine ("\nreflection.methodinfo"); A MyA=NewA (); B MyB=NewB (); //Get the Type and MethodInfo.Type Mytypea = Type.GetType ("A"); MethodInfo Mymethodinfoa=mytypea.getmethod ("Method"); Type Mytypeb= Type.GetType ("B"); MethodInfo Mymethodinfob= Mytypeb.getmethod ("Method"); //Get and display the Invoke method.Console.Write ("\nfirst Method-"+ Mytypea.fullname +"returns"+ Mymethodinfoa.invoke (MyA,NULL)); Console.Write ("\nsecond Method-"+ Mytypeb.fullname +"returns"+ Mymethodinfob.invoke (MyB,NULL)); return 0; }}