什麼是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);
}
}然而,在拆箱中,儲存在堆記憶體中的物件的值會複製到儲存在堆疊上的值型別。它具有顯式轉換,而裝箱具有隱式轉換。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP