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.