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