Original link Address: http://blog.csdn.net/lanruoshui/article/details/5090710
The principle is as follows:
1. Dynamic loading and invocation using reflection.
Assembly Assembly=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");//Use type namespaces and names to get the 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:
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
Mi. Invoke (obj,params[]);//based on the parameter line method, the return value is the return value of the original method
Object Obj=null; Byte[] Filesbyte; Assembly Assembly; Type type; MethodInfo timerinitial; MethodInfo Timerdispose; #endregion private void Loaddll ()//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:http://msdn.microsoft.com/en-us/library/a89hcwhh.aspx
1 Public classA2 { 3 Public Virtual intMethod () {return 0;} 4 } 5 6 Public classB7 { 8 Public Virtual intMethod () {return 1;} 9 } Ten One classMymethodinfo A { - Public Static intMain () - { theConsole.WriteLine ("/nreflection.methodinfo"); -A MyA =NewA (); -B MyB =NewB (); - + //Get the Type and MethodInfo. -Type Mytypea = Type.GetType ("A"); +MethodInfo Mymethodinfoa = Mytypea.getmethod ("Method"); A atType 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)); inConsole.Write ("/nsecond Method-"+ Mytypeb.fullname + - "returns"+ Mymethodinfob.invoke (MyB,NULL)); to return 0; + } -}
C # dynamic load (GO)