📜  C#中装箱和拆箱的区别

📅  最后修改于: 2021-05-29 21:14:14             🧑  作者: Mango

装箱和拆箱是C#中的重要概念。 C#类型系统包含三种数据类型:值类型(int,char等)引用类型(对象)指针类型。基本上,它将值类型转换为引用类型,反之亦然。装箱和拆箱可实现类型系统的统一视图,在该系统中,任何类型的值都可以视为对象。

Boxing Unboxing
It convert value type into an object type. It convert an object type into value type.
Boxing is an implicit conversion process. Unboxing is the explicit conversion process.
Here, the value stored on the stack copied to the object stored on the heap memory. Here, the object stored on the heap memory copied to the value stored on the stack .
Example:
// C# program to illustrate Boxing
using System;
  
public class GFG {
    static public void Main()
    {
        int val = 2019;
  
        // Boxing
        object o = val;
  
        // Change the value of val
        val = 2000;
  
        Console.WriteLine("Value type of val is {0}", val);
        Console.WriteLine("Object type of val is {0}", o);
    }
}

Output:

Value type of val is 2000
Object type of val is 2019
Example:
// C# program to illustrate Unboxing
using System;
  
public class GFG {
    static public void Main()
    {
        int val = 2019;
  
        // Boxing
        object o = val;
  
        // Unboxing
        int x = (int)o;
  
        Console.WriteLine("Value of o is {0}", o);
        Console.WriteLine("Value of x is {0}", x);
    }
}

Output:

Value of o is 2019
Value of x is 2019