CIL / MSIL拳击问题?

时间:2016-10-23 22:14:45

标签: cil boxing

我以为我知道拳击和拆箱是如何工作的,但显然我没有,因为我期望正确编译,

// the start of my Program::Main()
.maxstack 8 // Yes I know it's a large stack size for
            // the given method; it's just a test program ;)
.entrypoint
ldc.i4  10
box     int32
unbox   int32 // Removing these two lines
box     int32 // makes it run properly
call    void [mscorlib]System.Console::WriteLine(object)
ret

反而抛出错误“Invalid IL code in Program:Main(): box 0x1b000004。”

根据我的理解,操作是这样的:

// instruction:        stack after instruction is run:
   ldc.i4 10        // 10
   box int32        // object(int32,10)
   unbox int32      // 10
   box int32        // should be object(int32,10), but instead, got an error.

我尝试删除拆箱并重新装箱,它运行正常。此外,删除对WriteLine的调用和第二次装箱,只留下一个int,然后从堆栈中丢弃int运行正常。由于一些奇怪的原因,装箱,拆箱,然后重新装箱会引发错误。

那么,在第二次装箱期间有什么不同会导致它抛出错误而不是像第一次那样执行?

1 个答案:

答案 0 :(得分:3)

unbox将指向值的托管指针推送到评估堆栈,而不是值本身。请尝试使用unbox.any。 - Lee

相关问题