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;

      // The change in x won't affect the value of ob
      System.Console.WriteLine("Value Type = {0}", x);
      System.Console.WriteLine("Oject Type = {0}",ob);
   }
}

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

更新于: 2020 年 6 月 21 日

448 次观看

启动你的 职业

完成课程即可获得认证

开始
广告
© . All rights reserved.