According to industry practices, we use the simplest example:"Hello World"To start ourEmitTour. ExamplesCodeAnd the annotations are as follows:
Using System;
Using System. Collections. Generic;
Using System. text;
Using System. reflection. emit;
Namespace Emitexamples. helloworld
{
Class Program
{
/// <Summary>
/// Delegate used to call a dynamic method
/// </Summary>
Private Delegate Void Helloworlddelegate ();
Static Void Main ( String [] ARGs)
{
// Defines a dynamic method named helloworld with no return value and no parameters
Dynamicmethod helloworldmethod = New Dynamicmethod ( " Helloworld " , Null , Null );
//Create an msil generator to generate code for dynamic methods
Ilgenerator helloworldil=Helloworldmethod. getilgenerator ();
// Hello world! Create and load characters on the stack
Helloworldil. emit (Opcodes. ldstr, " Hello world! " );
// Call the console. writeline (string) method to output Hello world!
Helloworldil. emit (Opcodes. Call, Typeof (Console). getmethod ( " Writeline " , New Type [] { Typeof ( String )}));
// Method end, return
Helloworldil. emit (Opcodes. Ret );
// create a dynamic method, obtain a delegate that can execute this dynamic method
helloworlddelegate helloworld = (helloworlddelegate) helloworldmethod. createdelegate ( typeof (helloworlddelegate ));
//Execute the dynamic method and print Hello World on the screen!
Helloworld ();
}
}
}
Helloworld
Here we just use this exampleEmitAndIlYou can get an intuitive understanding of the methods used in this document.ProgramSource code downloadHelloworld.