使用Emit动态生成代码

       /** 使用Emit动态生成代码 **/
            //创建程序集
            var builder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("EmitTest"), AssemblyBuilderAccess.RunAndSave);
            //创建模块
            var module = builder.DefineDynamicModule("Main", "Main.exe");
            //定义类
            var type = module.DefineType("Hello", TypeAttributes.Public) ;
            //定义方法 (方法名、访问属性、返回值、参数)
            var method = type.DefineMethod("SayHello", MethodAttributes.Public | MethodAttributes.Static, null, null);
            //获取IL生成器
            var il = method.GetILGenerator();
            il.Emit(OpCodes.Ldstr, "Hello world");//ldStr:加载一个字符串到evaluation stack。
            il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));//Call:调用方法。
            il.Emit(OpCodes.Call, typeof(Console).GetMethod("ReadLine"));
            il.Emit(OpCodes.Pop);//读入的值会被推送至evaluation stack,而本方法是没有返回值的,因此,需要将栈上的值抛弃 
            il.Emit(OpCodes.Ret);//Ret:返回,当evaluation stack有值时会返回栈顶值。
            var t = type.CreateType();
            builder.SetEntryPoint(t.GetMethod("SayHello"));
            builder.Save("Main.exe");

  

猜你喜欢

转载自www.cnblogs.com/Seven77yixuan/p/10853539.html
今日推荐