学习 Programming C#: Attributes and Reflection
public class EmitHelloWorld
{
static void Main(string[] args)
{
// 创建动态程序集和模块
AssemblyName assemblyName = new AssemblyName();
assemblyName.Name = "HelloWorld";
// 定义动态程序集
AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder moduleBuider = assemblyBuilder.DefineDynamicModule("HelloWorld.exe");
// 创建类型
TypeBuilder typeBuilder = moduleBuider.DefineType("HelloWord", TypeAttributes.Public | TypeAttributes.Class);
// 创建Main方法
MethodBuilder methodBuilder = typeBuilder.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static, typeof(void), new Type[] { typeof(string[]) });
// 为Main方法创建IL代码
ILGenerator ilGenerator = methodBuilder.GetILGenerator();
ilGenerator.EmitWriteLine("Hello,World!");
ilGenerator.Emit(OpCodes.Ret);
// 创建实例
Type helloWorldType = typeBuilder.CreateType();
// 调用方法
helloWorldType.GetMethod("Main").Invoke(null, new string[] { null });
// 创建入口点
assemblyBuilder.SetEntryPoint(methodBuilder, PEFileKinds.ConsoleApplication);
// 保存
assemblyBuilder.Save("HelloWorld.exe");
}
}