什麼是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-06-21

448 次觀看

啟動您的 職業生涯

完成課程後獲取認證

開始學習
廣告
© . All rights reserved.