IL学习,使用Emit动态创建一个委托

前几天看了一下C# To IL 系列的文章,感觉写的不错,于是今天自己动手做了一个小低抹(demo),注释加上了自己的理解,以便加深记忆,如果有什么不对的地方,欢迎指正!

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Dynamic;


namespace ConsoleApplication1
{
    class Program
    {
        public delegate void TestHandle(string a);
        static void Main(string[] args)
        {
            DynamicMethod method = new DynamicMethod("Test", null, new Type[] { typeof(string) }, typeof(Program));//创建一个动态方法
            ILGenerator il = method.GetILGenerator();//获取IL生成器
            MethodInfo console = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) });
            il.Emit(OpCodes.Ldarg_0);//加载第0个参数到栈上供下面的方法使用,Ldarg_0可以解释为load argument of index 0
            il.Emit(OpCodes.Call, console);//调用Console.WriteLine()方法,Call解释为调用方法
            il.Emit(OpCodes.Ret);//方法结束指令(Ret,每个方法必须以这个指令结束)
            TestHandle thandle = method.CreateDelegate(typeof(TestHandle)) as TestHandle;//创建为委托
            thandle("不会吧!");//执行
        }
    }
}

---------知其然更要知其所以然

原文地址:https://www.cnblogs.com/netqiang/p/3286887.html