装箱和取消装箱

    技术2022-05-20  31

    将值类型转换为引用类型的过程称为装箱。装箱某个变量,就是创建一个引用变量,它指向堆上的新副本。引用变量是一个对象,因此,它可以使用每个对象都继承的所有方法(例如 ToString())。下面的代码进行了具体的说明:

    int i = 67; // i is a value type object o = i; // i is boxed System.Console.WriteLine(i.ToString()); // i is boxed

    在使用旨在用于对象的类时将会遇到取消装箱:例如,使用 ArrayList 存储整数。将某个整数存储在 ArrayList 中,即是对整数进行装箱。检索某个整数时,必须对它进行取消装箱。

    System.Collections.ArrayList list = new System.Collections.ArrayList(); // list is a reference type int n = 67; // n is a value type list.Add(n); // n is boxed n = (int)list[0]; // list[0] is unboxed


    最新回复(0)