装箱拆箱操作

装箱用于在垃圾回收堆中存储值类型,是值类型(C#参考)到object类型或到此值类型所实现的任何接口类型的隐式转换。对值类型装箱会在堆中分配一个对象实例,并将该值复制到新的对象中。

以下3段代码说明如何使用装箱拆箱操作,请尝试将其分别保存在不同的文件中并使用csc命令编译,然后分别运行查看效果:

  1. class TestBoxing  
  2. {  
  3.     static void Main()  
  4.     {  
  5.         int I = 123;  
  6.         object o = I;  // implicit boxing  
  7.  
  8.         I = 456;  // change the contents of i  
  9.  
  10.         System.Console.WriteLine("The value-type value = {0}", i);  
  11.         System.Console.WriteLine("The object-type value = {0}", o);  
  12.     }  
  13. }  
  14.  
  15.  
  16. class TestUnboxing  
  17. {  
  18.     static void Main()  
  19.     {  
  20.         int I = 123;  
  21.         object o = I;  // implicit boxing  
  22.  
  23.         try  
  24.         {  
  25.             int j = (short)o;  // attempt to unbox  
  26.  
  27.             System.Console.WriteLine("Unboxing OK.");  
  28.         }  
  29.         catch (System.InvalidCastException e)  
  30.         {  
  31.             System.Console.WriteLine("{0} Error: Incorrect unboxing.", e. Message);  
  32.         }  
  33.     }  
  34. }  
  35.  
  36.  
  37. class TestUnboxing  
  38. {  
  39.     static void Main()  
  40.     {  
  41.         int I = 123;  
  42.         object o = I;  // implicit boxing  
  43.  
  44.         try  
  45.         {  
  46.             int j = (int)o;            // attempt to unbox  
  47.  
  48.             System.Console.WriteLine("Unboxing OK.");  
  49.         }  
  50.         catch (System.InvalidCastException e)  
  51.         {  
  52.             System.Console.WriteLine("{0} Error: Incorrect unboxing.", e.Message);  
  53.         }  
  54.     }  
  55. }  
原文地址:https://www.cnblogs.com/shihao/p/2147186.html