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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值