什么是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