CIL / MSIL 拳击问题?

CIL / MSIL Boxing issue?

我以为我知道装箱和拆箱是如何工作的,但显然我不知道,因为我希望能正确编译,

// 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 运行正常。出于某种奇怪的原因,装箱、拆箱,然后重新装箱会引发错误。

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

unbox 将指向值的托管指针推送到计算堆栈上,而不是值本身。尝试改用 unbox.any。 – Lee