Boxing and Unboxing
Boxing and unboxing enable value types to be treated as objects. Boxing a value type packages it inside an instance of the Object reference type. This allows the value type to be stored on the garbage collected heap. Unboxing extracts the value type from the object. In this example, the integer variable i is boxed and assigned to object o.
int i = 123;
object o = (object)i; // boxing
| |
The object o can then be unboxed and assigned to integer variable i:
o = 123;
i = (int)o; // unboxing
Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates
an object instance on the heap and copies the value into the new object. Consider the following declaration of a value-type variable:
The following statement implicitly applies the boxing operation on the variable i:
int i = 123;
object o = (object)i; // explicit boxing
This example converts an integer variable i to an object o by using boxing. Then, the value stored in the variable i is changed from 123 to 456. The example shows that the original value type and the boxed object use separate memory locations, and therefore can store different values.
class TestBoxing { static void Main() { int i = 123; object o = i; // implicit boxing i = 456; // change the contents of i System.Console.WriteLine("The value-type value = {0}", i); System.Console.WriteLine("The object-type value = {0}", o); } } Output:
Example:
class TestUnboxing Output: Specified cast is not valid. Error: Incorrect unboxing.
If you change the statement: int j = (short)o; to: int j = (int)o;
the conversion will be performed, and you will get the output: Unboxing OK.
| |||||||||
装箱与拆箱
本文介绍了C#中装箱与拆箱的概念及操作过程。装箱是指将值类型转换为引用类型,允许值类型存储在垃圾回收堆上;拆箱则是从引用类型恢复到原始的值类型。通过实例演示了如何进行装箱与拆箱操作,并解释了它们对内存的影响。
124

被折叠的 条评论
为什么被折叠?



