码迷,mamicode.com
首页 > 其他好文 > 详细

boxing & unboxing

时间:2014-07-18 17:24:23      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   strong   os   

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.  

bubuko.com,布布扣
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只能对应同一类型,否则出错,见下例:

bubuko.com,布布扣
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

boxing & unboxing,布布扣,bubuko.com

boxing & unboxing

标签:style   blog   http   color   strong   os   

原文地址:http://www.cnblogs.com/tekkaman/p/3853206.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!