zoukankan      html  css  js  c++  java
  • 装箱拆箱操作

    装箱用于在垃圾回收堆中存储值类型,是值类型(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. }  
  • 相关阅读:
    本地MD5 SHA1 函数 的JS实现
    让用户减少学习成本——后台系统交互心得(二)(原创理论)
    样式库构建规范(转)
    基础css base.css(转)
    更贴近业务及用户——交互设计工作方式转变感言(原创理论)
    三栏布局,中间栏自适应
    你必须知道的【闭包】陷阱和案例-非常好
    css3 基础内容
    VB.Net实现登陆Ftp的方法
    .NET發送郵件功能開發
  • 原文地址:https://www.cnblogs.com/shihao/p/2147186.html
Copyright © 2011-2022 走看看