IL代码:
.method public hidebysig instance int32 Add ( int32 p1, int32 p2 ) cil managed { // Method begins at RVA 0x2050 // Code size 9 (0x9) .maxstack 2 .locals init ( [0] int32 CS$1$0000 ) IL_0000: nop IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: add IL_0004: stloc.0 IL_0005: br.s IL_0007 IL_0007: ldloc.0 IL_0008: ret }
C#代码:
public delegate int Populator(int p1, int p2); public void EmitAdd() { var dynamicMethod = new DynamicMethod("DoAdd", typeof(int), new Type[] { typeof(int), typeof(int) }); var il = dynamicMethod.GetILGenerator(); var label = il.DefineLabel(); var retlbl = il.DeclareLocal(typeof(int)); il.Emit(OpCodes.Nop); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Ldarg_2); il.Emit(OpCodes.Add); il.Emit(OpCodes.Stloc_0); il.Emit(OpCodes.Br_S, label); il.MarkLabel(label); il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Ret); var act = (Populator)dynamicMethod.CreateDelegate(typeof(Populator)); var r = act(1, 2); }
调用总是报:请求的操作对 DynamicMethod 无效。