开箱机制

Mechanism of Unboxing

当拆箱发生时,会将装箱值复制到适当的变量类型中,但在堆上装箱副本的内存位置会发生什么。 盒装副本是否保留在该位置并覆盖堆上的内存?

Is boxed copy remain at that location and cover memory on heap?

是的。毕竟,可能还有其他参考资料:

object o1 = 5;
object o2 = o1;
int x = (int) o1;
x = 10;
Console.WriteLine(o2); // Still 5

装箱值就像普通对象一样,在没有更多强引用时有资格进行垃圾回收。

是的,当然,开箱时,原件始终不受影响。

在 IL 级别下,有两个用于拆箱的操作码:unbox.anyunbox

根据 MSDN,regarding unbox.any:

When applied to the boxed form of a value type, the unbox.any instruction extracts the value contained within obj (of type O), and is therefore equivalent to unbox followed by ldobj.

regarding unbox:

[...] unbox is not required to copy the value type from the object. Typically it simply computes the address of the value type that is already present inside of the boxed object.

因此,可能会或可能不会复制原始值,但原始值始终不受影响。