【发布时间】:2017-03-05 15:14:10
【问题描述】:
我以为我知道装箱和拆箱的工作原理,但显然我不知道,因为我期望正确编译,
// 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。 -
是的,解决了它。你应该从你的评论中做出答案:)