按照業界的慣例,我們用一個最簡單的例子——“Hello World”,來開始我 們的Emit之旅。例子的相關代碼及注釋如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection.Emit;
namespace EmitExamples.HelloWorld
{
class Program
{
/// <summary>
/// 用來調用動態方法的委托
/// </summary>
private delegate void HelloWorldDelegate();
static void Main(string[] args)
{
//定義一個名為HelloWorld的動態方法,沒有返回值,沒有參數
DynamicMethod helloWorldMethod = new DynamicMethod("HelloWorld", null, null);
//創建一個MSIL生成器,為動態方法生成代碼
ILGenerator helloWorldIL = helloWorldMethod.GetILGenerator();
//將要輸出的Hello World!字符創加載到堆棧上
helloWorldIL.Emit(OpCodes.Ldstr, "Hello World!");
//調用Console.WriteLine(string)方法輸出Hello World!
helloWorldIL.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));
//方法結束,返回
helloWorldIL.Emit(OpCodes.Ret);
//完成動態方法的創建,並且獲取一個可以執行該動態方法的委托
HelloWorldDelegate HelloWorld = (HelloWorldDelegate)helloWorldMethod.CreateDelegate(typeof(HelloWorldDelegate));
//執行動態方法,將在屏幕上打印Hello World!
HelloWorld();
}
}
}
這裡我們只是用這個例子讓大家對Emit以及IL有個直觀的了解,其中用到的方 法將在以後的章節中具體講解
本文配套源碼