装箱用于在垃圾回收堆中存储值类型,是值类型(C#参考)到object类型或到此值类型所实现的任何接口类型的隐式转换。对值类型装箱会在堆中分配一个对象实例,并将该值复制到新的对象中。
以下3段代码说明如何使用装箱拆箱操作,请尝试将其分别保存在不同的文件中并使用csc命令编译,然后分别运行查看效果:
- 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);
- }
- }
- class TestUnboxing
- {
- static void Main()
- {
- int I = 123;
- object o = I; // implicit boxing
- try
- {
- int j = (short)o; // attempt to unbox
- System.Console.WriteLine("Unboxing OK.");
- }
- catch (System.InvalidCastException e)
- {
- System.Console.WriteLine("{0} Error: Incorrect unboxing.", e. Message);
- }
- }
- }
- class TestUnboxing
- {
- static void Main()
- {
- int I = 123;
- object o = I; // implicit boxing
- try
- {
- int j = (int)o; // attempt to unbox
- System.Console.WriteLine("Unboxing OK.");
- }
- catch (System.InvalidCastException e)
- {
- System.Console.WriteLine("{0} Error: Incorrect unboxing.", e.Message);
- }
- }
- }