生成DLL

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

namespace EmitDemo
{
    public class DLLCreator
    {
        public static void Main(string[] arsg)
        {
            var asmName = new AssemblyName("Test");
            var asmBuider = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave);
            var mdlbldr = asmBuider.DefineDynamicModule("Hello", "Hello.exe");
            var typebldr = mdlbldr.DefineType("Hello", TypeAttributes.Public);
            var methodbldr = typebldr.DefineMethod("SayHello", MethodAttributes.Public | MethodAttributes.Static, null, null);
            var il = methodbldr.GetILGenerator();
            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();
            asmBuider.SetEntryPoint(t.GetMethod("SayHello"));
            asmBuider.Save("Hello.exe");
        }
    }
}
原文地址:https://www.cnblogs.com/ziranquliu/p/4651173.html