AppDomain.DefineDynamicAssembly
using System;
using System.Reflection;
using System.Reflection.Emit;
public class MainClass
{
public static void Main()
{
AppDomain ad = AppDomain.CurrentDomain;
AssemblyName an = new AssemblyName();
an.Name = "DynamicRandomAssembly";
AssemblyBuilder ab = ad.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run);
ModuleBuilder mb = ab.DefineDynamicModule("RandomModule");
TypeBuilder tb = mb.DefineType("DynamicRandomClass",TypeAttributes.Public);
Type returntype = typeof(int);
Type[] paramstype = new Type[0];
MethodBuilder methb=tb.DefineMethod("DynamicRandomMethod", MethodAttributes.Public, returntype, paramstype);
ILGenerator gen = methb.GetILGenerator();
gen.Emit(OpCodes.Ldc_I4, 1);
gen.Emit(OpCodes.Ret);
Type t = tb.CreateType();
Object o = Activator.CreateInstance(t);
Object[] aa = new Object[0];
MethodInfo m = t.GetMethod("DynamicRandomMethod");
int i = (int) m.Invoke(o, aa);
Console.WriteLine("Method {0} in Class {1} returned {2}",m, t, i);
}
}
using System;
public class DynamicRandomClass
{
public int DynamicRandomMethod()
{
return 1;
}
}
Related examples in the same category