在数组中存储元素时,ILGenerator会发出Break指令

Der*_*mot 3 cil reflection.emit

我正在使用ILGenerator.Emit生成动态类型.我正在生成一个方法体,它将方法参数的类型存储在一个数组中.为了实际存储数组中的元素,我循环遍历给定方法的参数并构建必要的IL来存储元素.在第二次迭代中,在Stelem.ref (下面的L_003d )指令之后出现Break 指令.这总是发生在第二次迭代,我无法弄清楚为什么.这是代码:

        ilGenerator.Emit(OpCodes.Ldc_I4, exampleMethod.GetParameters().Length);
        ilGenerator.Emit(OpCodes.Newarr, typeof(Type));
        ilGenerator.Emit(OpCodes.Stloc, typeArray);

        for (int idx = 0; idx < exampleMethod.GetParameters().Length; idx++)
        {
            ilGenerator.Emit(OpCodes.Ldloc, typeArray);
            ilGenerator.Emit(OpCodes.Ldc_I4, idx);
            ilGenerator.Emit(OpCodes.Ldarg, idx + 1);
            ilGenerator.Emit(OpCodes.Box, typeof(int));
            ilGenerator.EmitCall(OpCodes.Callvirt, typeof(object).GetMethod("GetType"), null);
            ilGenerator.Emit(OpCodes.Stelem_Ref, idx);//second iteration causes a break to be output in the IL
        }

        ilGenerator.Emit(OpCodes.Ret);
Run Code Online (Sandbox Code Playgroud)

并且IL输出在这里

.method public virtual instance int32 Add3(int32, int32, int32) cil managed
 {
.maxstack 3
.locals init (
    [0] class [mscorlib]System.Type[] typeArray)
L_0000: ldc.i4 3
L_0005: newarr [mscorlib]System.Type
L_000a: stloc.0 
L_000b: ldloc.0 
L_000c: ldc.i4 0
L_0011: ldarg A_0
L_0015: nop 
L_0016: nop 
L_0017: box int32
L_001c: callvirt instance class [mscorlib]System.Type [mscorlib]System.Object::GetType()
L_0021: stelem.ref 
L_0022: nop 
L_0023: nop 
L_0024: nop 
L_0025: nop 
L_0026: ldloc.0 
L_0027: ldc.i4 1
L_002c: ldarg A_1
L_0030: nop 
L_0031: nop 
L_0032: box int32
L_0037: callvirt instance class [mscorlib]System.Type [mscorlib]System.Object::GetType()
L_003c: stelem.ref 
**L_003d: break** 
L_003e: nop 
L_003f: nop 
L_0040: nop 
L_0041: ldloc.0 
L_0042: ldc.i4 2
L_0047: ldarg A_2
L_004b: nop 
L_004c: nop 
L_004d: box int32
L_0052: callvirt instance class [mscorlib]System.Type [mscorlib]System.Object::GetType()
L_0057: stelem.ref 
L_0058: ldarg.0 
L_0059: nop 
L_005a: nop 
L_005b: nop 
L_005c: ret 
}
Run Code Online (Sandbox Code Playgroud)

任何指针或建议将不胜感激.

非常感谢

德莫特

Fra*_*nov 5

break的操作码是0x01,顺便提一下,你也是作为参数传递给stelem.ref emit的idx值.请注意,在第三次迭代中有一个额外的ldarg.0(其中idx为2).

您不应该为stelem emit指定参数.