class Program
{
static void Main(string[] args)
{
var gen = BuildDynType();
var genInst = Activator.CreateInstance(gen, new object[0]);
gen.InvokeMember("DoAdd", // название метода, который создал
BindingFlags.InvokeMethod, // биндинг на вызов
null, // биндер здесь не нужен
genInst, // тип, в котором метод
new object[]{5, 6}); // передача аргументов в метод (должны совпадать типы 1к1)
}
public static Type BuildDynType() {
Type addType = null;
AppDomain currentDom = Thread.GetDomain();
AssemblyName myAsmName = new AssemblyName();
myAsmName.Name = "MyDynamicAssembly";
AssemblyBuilder myAsmBldr = currentDom.DefineDynamicAssembly(
myAsmName,
AssemblyBuilderAccess.RunAndSave);
// The dynamic assembly space has been created. Next, create a module
// within it. The type Point will be reflected into this module.
ModuleBuilder myModuleBldr = myAsmBldr.DefineDynamicModule("MyModule");
TypeBuilder myTypeBldr = myModuleBldr.DefineType("Adder");
MethodBuilder myMthdBldr = myTypeBldr.DefineMethod("DoAdd",
MethodAttributes.Public |
MethodAttributes.Static,
typeof(void),
new Type[]
{typeof(int), typeof(int)});
// Build the array of Bytes holding the MSIL instructions.
var ILGen = myMthdBldr.GetILGenerator();
byte[] ILcodes = new byte[] {
0x02, /* 02h is the opcode for ldarg.0 */
0x03, /* 03h is the opcode for ldarg.1 */
0x58, /* 58h is the opcode for add */
0x0A, /* 0Ah is the opcode for stloc.0 */
0x2A /* 2Ah is the opcode for ret */
};
var localSig = SignatureHelper.GetLocalVarSigHelper(myModuleBldr);
localSig.AddArgument(typeof(int));
var localSigArray = localSig.GetSignature();
ILGen.DeclareLocal(typeof(Int32));
myMthdBldr.SetMethodBody(ILcodes, 8, localSigArray, null, null);
addType = myTypeBldr.CreateType();
return addType;
}
}