Let's take a look at the following code:
1: int tempi = 1;
2: object o = tempi;
3: double tempd = (double) o;
It can be passed during compilation, but the following error is reported during runtime:
System. invalidcastexception: the specified conversion is invalid.
This is because, when unpacking an object, the result of the transformation must be its original unboxed type. In this case, you must first convert the data type to the int type before converting it to the double type. The correct format is as follows:
1: int tempi = 32;
2: object o = tempi;
3: double tempd = (double)(int) o;
In the. NET Framework, boxing usually consists of the following three steps:
1. allocate memory for the newly generated reference type object from the managed heap. The allocated memory size is the size of the boxed Value Type instance, plus a method table pointer and a syncblockindex for the newly generated reference type.
2. Copy the field of the Value Type instance to the memory of the newly allocated object on the hosting heap.
3. Return the address of the newly allocated object in the managed heap. In this way, the value type Instance becomes a reference type object.
The unboxing process is as follows:
1. If the object to be split is null, an nullreferenceexception will be thrown.
2. If the referenced object is not a boxed object of the expected value type, the unboxing fails and an invalidcastexception (such as the beginning part of this article) is thrown ).
3. A pointer pointing to the value type of the boxed object is returned. The Value Type pointed to by this pointer does not know anything about the additional member (that is, a method table pointer and a syncblockindex) of the referenced type object. In fact, this pointer points to the unpacked part of the boxed object (Microsoft. NET Framework Program Design <revision> ).
The above example can be used to help understand the 3rd point. First, define the value type variable tempi, which occupies 4 bytes in the memory. After packing, it becomes a reference object and adds a method table pointer and a syncblockindex. For a reference type, you only need to pass a "reference type" address to obtain its value, method table pointer, and syncblockindex. During unpacking, the address of its "value" (unpacked part) is passed, that is, an address of the "int (int32) type" (reference ), it can only read 4 bytes. The double type is 8 bytes, so the implicit conversion will report an error. You need to convert it to the int type before conversion to the double type.