什么是C#中的拳击?

装箱将值类型转换为对象类型。让我们看一个拳击的例子-

int x = 50;
object ob = x; // boxing

在装箱中,将存储在堆栈中的值复制到存储在堆内存中的对象,而取消装箱则相反。

装箱对将值类型存储在垃圾回收堆中很有用。它是将值类型隐式转换为类型对象。

让我们看一个例子-

示例

using System;
using System.Collections.Generic;
using System.Linq;

public class Demo {

   static void Main() {
      int x = 50;
      object ob = x;

      x = 100;

      //x的变化不会影响ob的值
      System.Console.WriteLine("Value Type = {0}", x);
      System.Console.WriteLine("Oject Type = {0}",ob);
   }
}

但是,在“拆箱”中,将存储在堆内存中的对象的值复制到存储在堆栈中的值类型。它具有显式转换,而装箱具有隐式转换。