The previous Hello World example should have let us have a vague understanding of emit, then what is emit in the end what kind of thing, he can achieve what function? Yesterday to check some information, roughly summed up, because only began to learn there must be imperfect place, I hope we can criticize.
1. What is reflection emit (Reflection Emit)
Emit should be a relatively advanced feature of reflection, and when it comes to reflection, you should be familiar with reflection, which discovers information about objects at run time, and executes those objects (creating object instances, executing methods on objects). This feature is made up of. NET is provided by the class of the System.Reflection namespace. Simply put, they not only allow you to browse through the exposed classes, methods, properties, and fields of an assembly, but also allow you to create instances of a type and execute methods on those types (call members). These features are great for discovering objects at run time, but the reflection mechanism of. NET does not end there. Reflection also allows you to build an assembly at run time, and you can create entirely new types. This is the reflection emit (reflection emit).
Using emit, you can start from scratch, dynamically construct assemblies and types, generate code dynamically when needed, and increase the flexibility of the program. With these features, we can use them to implement some of the typical applications, such as:
L Dynamic Agent (AOP);
• Reduce reflection loss of performance (Dynamic method, etc.);
L ORM Implementation;
L Tools and IDE plugin development;
• Development of common code security modules.
2. Full process of using emit
Using emit typically involves the following steps:
1 Create a new assembly (you can choose to exist in memory or persisted to the hard disk);
2 Create a module within the assembly;
3 Create dynamic classes within the module;
4 Add dynamic methods, attributes, events, etc. to dynamic classes;
5 Generate the relevant IL code;
6) Return the created type or persist to the hard disk.
Of course, if you just want to create a dynamic method, you can use the DynamicMethod class used in the previous HelloWorld example to create a dynamical approach and pass in the constructor with the class or module it relies on. Looking at this process, I believe you have an intuitive understanding of the process of using emit to create dynamic types, so we can deepen our understanding of this process by implementing a class that asks for the Fibonacci sequence.