In accordance with the industry's practice, we use one of the simplest examples-"Hello world"-to begin our emit journey. The relevant code and comments for the example are as follows:
using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Reflection.Emit;
Namespace Emitexamples.helloworld {class Program {///<summary>///a delegate to invoke a dynamic method
</summary> Private delegate void Helloworlddelegate (); static void Main (string[] args) {//define a dynamic method named HelloWorld, no return value, no parameter DynamicMethod hell
Oworldmethod = new DynamicMethod ("HelloWorld", NULL, NULL);
Create an MSIL generator to generate code for the dynamic method ILGenerator Helloworldil = Helloworldmethod.getilgenerator ();
The Hello world! word that will be output is Fuganga loaded onto the stack helloworldil.emit (opcodes.ldstr, "Hello world!");
Call Console.WriteLine (string) method output Hello world! Helloworldil.emit (Opcodes.call, typeof (Console).
GetMethod ("WriteLine", new type[] {typeof (String)}));
Method ends, returns Helloworldil.emit (Opcodes.ret); Completes the creation of the dynamic method, and gets the one that can execute the dynamic sideThe commission of the law helloworlddelegate HelloWorld = (helloworlddelegate) helloworldmethod.createdelegate (typeof (Helloworlddel
egate));
Executes the dynamic method that will print the Hello world! on the screen
HelloWorld (); }}
Here we just use this example to give you an intuitive understanding of emit and IL, and the methods used will be specifically explained in later chapters
This article supporting source code