CLR 是怎样去处理Boxing and Unboxing Value Types?

来源:互联网 发布:林天宝知乎 编辑:程序博客网 时间:2024/04/18 13:28

It's possible to convert a value type to a reference type by using a mechanism called boxing.
Internally, here's what happens when an instance of a value type is boxed:
1. Memory is allocated from the managed heap. The amount of memory allocated is the size
required by the value type's fields plus the two additional overhead members (the type
object pointer and the sync block index) required by all objects on the managed heap.
2. The value type's fields are copied to the newly allocated heap memory.
3. The address of the object is returned. This address is now a reference to an object; the
value type is now a reference type.

Unboxing is not the exact opposite of boxing. The unboxing operation is much less costly
than boxing.
Internally, here's exactly what happens when a boxed value type instance is unboxed:
1. If the variable containing the reference to the boxed value type instance is null,
a NullReferenceException is thrown.
2. If the reference doesn't refer to an object that is a boxed instance of the desired value
type, an InvalidCastException is thrown

原创粉丝点击