zoukankan      html  css  js  c++  java
  • boxing & unboxing

    boxing & unboxing

      Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit. The concept of boxing and unboxing underlies the C# unified view of the type system in which a value of any type can be treated as an object.  

    int i = 123;
    // The following line boxes i.
    object o = i;  
    
    o = 123;
    i = (int)o;  // unboxing
    View Code

      In relation to simple assignments, boxing and unboxing are computationally expensive processes. When a value type is boxed, a new object must be allocated and constructed. To a lesser degree, the cast required for unboxing is also expensive computationally. For more information, see Performance.

      Unboxing只能对应同一类型,否则出错,见下例:

    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);
            }
        }
    }
    View Code

    参考:http://msdn.microsoft.com/zh-cn/library/yz2be5wk.aspx

  • 相关阅读:
    设计模式Day02
    OA,ERP等源码一部分演示
    第三方登录
    其实没那么复杂!探究react-native通信机制
    学习面试题(day01)
    学习面试题Day02
    学习面试题Day03
    python 字典排序
    Mac系统下adb工具的配置
    Mac adb 安装
  • 原文地址:https://www.cnblogs.com/tekkaman/p/3853206.html
Copyright © 2011-2022 走看看