Emit:IL学习

Emit:IL学习
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Reflection.Emit;

using System.Reflection;



namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            var asmName = new AssemblyName("Test");



            var asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(



                asmName,



                AssemblyBuilderAccess.RunAndSave);



            var mdlBldr = asmBuilder.DefineDynamicModule("Main", "Main.exe");



            var typeBldr = mdlBldr.DefineType("Hello", TypeAttributes.Public);



            var methodBldr = typeBldr.DefineMethod(



                "SayHello",



                MethodAttributes.Public | MethodAttributes.Static,



                null,//return type               



                null//parameter type       



                );



            var il = methodBldr.GetILGenerator();//获取il生成器  



            il.Emit(OpCodes.Ldstr, "Hello, World");



            il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));



            il.Emit(OpCodes.Call, typeof(Console).GetMethod("ReadLine"));



            il.Emit(OpCodes.Pop);//读入的值会被推送至evaluation stack,而本方法是没有返回值的,因此,需要将栈上的值抛弃    



            il.Emit(OpCodes.Ret);



            var t = typeBldr.CreateType();



            asmBuilder.SetEntryPoint(t.GetMethod("SayHello"));



            asmBuilder.Save("Main.exe");

        }

    }

}
View Code

 

你可能感兴趣的:(it)