In. Net, the Assembly (Assembly) holds the metadata (MetaData) information, so you can parse the metadata to get the contents of the assembly, such as classes, methods, properties, and so on, which greatly facilitates the dynamic creation of instances at run time.
Main uses:
- Dynamically loading DLLs to implement plug-in mechanisms.
- Instantiates a type in a DLL.
- Performs late binding to access methods of types created at run time.
First, create a new blank solution: Dllsolution
Add a class library to your solution: Refdll, which will be an assembly that needs to be created dynamically
Rename the default new Class1 class: Student, this class will be a class that needs to be created dynamically. has a Name property and a SayHello method
namespace refdll{ public class Student { public string Name {get ; set ;} public void SayHello (string content) {Console.WriteLine ( string . Format ( {0} say {1} to everybody. "
Add a console project to the solution: Consoleapplication, set as Startup item
The code is as follows:
//Add ReferenceusingSystem.Reflection;namespaceconsoleapplication{classProgram {Static voidMain (string[] args) { //1, the method passed in is the name of the DLL, the DLL must refer to the//var asmload = assembly.load ("Refdll"); //2, this loadfile most convenient, parameter is the path of the DLL varAsmload = Assembly.loadfile (@"C:\Users\lenovo\Desktop\DllSolution\RefDll\bin\Debug\RefDll.dll"); //3, this method can also, parameters are also DLL path//var asmload = Assembly.LoadFrom (@ "C:\Users\lenovo\Desktop\DllSolution\RefDll\bin\Debug\RefDll.dll"); //gets the type of the class, Namespace + class name varType = Asmload.gettype ("refdll.student"); //create an instance of the class, Namespace + class name varInstance = Asmload.createinstance ("refdll.student"); //set the value of an attribute in an instanceType. GetProperty ("Name"). SetValue (instance,"Zhangsan",NULL); //getting methods in a class varmethod = Type. GetMethod ("SayHello"); //Calling MethodsMethod. Invoke (instance,New Object[] {"Hello" }); Console.read (); } }}
Result:Zhangsan say hello to everybody.
Using reflection to dynamically create an instance and invoke a method