In the same modulebuilder, after definetype and createtype, you can continue definetype .. this prevents too many assemblybuilder problems caused by code compilation. now only one assemblybuilder is required. this discovery is very meaningful for the Web framework. because the Web framework contains a large number of script files. with this feature, script files can be compiled separately with confidence.
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
static public class EmitTest
{
static public void Go()
{
AssemblyBuilder asm = AppDomain.CurrentDomain.DefineDynamicAssembly(
new AssemblyName("EmitTest"), AssemblyBuilderAccess.Run);
ModuleBuilder mdl=asm.DefineDynamicModule("EmitTestModule");
RunType(mdl, "Type1", "Method1", "Hello");
RunType(mdl, "Type2", "Method2", "World");
}
private static void RunType(ModuleBuilder mdl,string typename
,string methodname,string writestring)
{
TypeBuilder t1 = mdl.DefineType(typename);
MethodBuilder mb1 = t1.DefineMethod(methodname
, MethodAttributes.Static | MethodAttributes.Public, typeof(void), new Type[] { });
ILGenerator g1 = mb1.GetILGenerator();
g1.Emit(OpCodes.Ldstr, writestring);
g1.Emit(OpCodes.Call, typeof(EmitTest).GetMethod("WriteLine"));
MethodInfo mi1 = t1.CreateType().GetMethod(methodname);
mi1.Invoke(null, null);
}
[System.Runtime.CompilerServices.MethodImpl(
System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
static public void WriteLine(string str)
{
MethodBase caller=new System.Diagnostics.StackFrame(1).GetMethod();
Console.WriteLine(caller.DeclaringType.Assembly.FullName);
Console.WriteLine(str);
}
}