Cil ILGenerator在数组中存储元素时发出中断指令

Cil ILGenerator在数组中存储元素时发出中断指令,cil,reflection.emit,Cil,Reflection.emit,我正在使用ILGenerator.Emit生成动态类型。我正在生成一个方法体,它将在数组中存储方法参数的类型。为了实际存储数组中的元素,我将遍历给定方法的参数,并建立必要的IL来存储元素。在第二次迭代中,一条中断指令出现在Stelem.ref(下面的L_003d)指令之后。这总是发生在第二次迭代中,我不知道为什么。代码如下: ilGenerator.Emit(OpCodes.Ldc_I4, exampleMethod.GetParameters().Length);

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

        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);
如有任何指示或建议,将不胜感激

非常感谢


Dermot

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


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

非常感谢您的快速响应和解释,我永远不会得到它。不管怎么说,按照你的建议做了,它成功了。再次干杯。
.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 
}