《C#数据结构与算法》–2020 最新精讲版_2-6装箱和拆箱 笔记
文章目录
学习视频以及前言回顾
《C#数据结构与算法》–2020 最新精讲版_2-6装箱和拆箱 视频
《C#数据结构与算法》–2020 最新精讲版 2-5 动态数组 笔记
一、什么是装箱和拆箱
1、装箱和拆箱的基础概念
装箱:将值类型转换为引用类型
(用于在垃圾回收堆中储存值类型。装箱是值类型到Object类型或到此类型所实现的任何接口类型的隐式转换。)
代码如下(示例):
int i=12;
//此过程为装箱
object obj=i;
Console.WriteLine("i的输出:"+i);
Console.WriteLine("obj的输出:"+obj);
Console.ReadKey();
i的输出:12
obj的输出:12
拆箱:将引用类型转换为值类型
(从object类型到值类型或从接口类型到实现该接口的值类型的显示转换。)
代码如下(示例):
int i=12;
//此过程为装箱
object obj=i;
//此过程为拆箱
int j=(int)obj;
Console.WriteLine("i的输出:"+i);
Console.WriteLine("obj的输出:"+obj);
Console.WriteLine("拆箱后的输出:" + j);
Console.ReadKey();
i的输出:12
obj的输出:12
拆箱后的输出:12
注:所谓的拆箱,就是装箱操作的反操作,把堆中的对象复制到堆栈中,并且返回其值。需要注意的是,拆箱操作将判断被拆箱的对象类型和将要被复制的值类型引用是否一致,如果不一致,将会抛出一个InvalidCastException的异常。这里的类型匹配并不采用任何显示的类型转换。
try
{
Int32 i = 12;
//装箱
object obj = i;
//拆箱,转化类型不同
Int16 j = (Int16)obj;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadKey();
指定的转换无效。
解决方法:Ⅰ、Int16 j = (Int32)obj;
Ⅱ、Int16 j = (Int16)(Int32)obj;
2、数据类型
3、延申
问:以下程序中出现几次装箱?几次拆箱呢?
int i=0;
Object obj=i;
Console.WriteLine(i+","+(int)obj);
答:这个程序中出现了三次装箱,一次拆箱。
装箱1:将i
转化成object
类型,而object
类型为引用类型
装箱2:输出的时候将i
转换成string
类型,而string
类型为引用类型
装箱3:输出的时候将(int)obj
转换成string
类型,而string
类型为引用类型
拆箱:(int)obj
将object
类型转化成int
类型,而int
类型为值类型
二、List与ArrayList
ArrayList:需要首先将类型转变为Object也就是装箱的问题,然后再将Object转换为其所对应的类型也就是拆箱的操作
List:因为泛型中指定了类型所以其不需要进行装箱拆箱操作,效率也就相对提升
代码如下(示例):
int n = 10000000;
Stopwatch t1 = new Stopwatch();
Stopwatch t2 = new Stopwatch();
t1.Start();
List<int> l = new List<int>();
for(int i=0;i<n;i++)
{
l.Add(i);//不发生装箱
int x =l[i];//不发生拆箱
}
t1.Stop();
Console.WriteLine("List'time" + t1.ElapsedMilliseconds+"ms");//时间计算
t2.Start();
ArrayList a = new ArrayList();
for (int i = 0; i < n; i++)
{
a.Add(i);//发生装箱
int x = (int)a[i];//发生拆箱
}
t2.Stop();
Console.WriteLine("ArrayList'time" + t2.ElapsedMilliseconds + "ms");//时间计算
List与ArrayList之间的区别在于,List不存在装箱,而ArrayList存在着装箱行为,要输出的时候需要先进行拆箱操作,所以更加耗时。
(示例运行结果):
List'time169ms
ArrayList'time1382ms
三、拓展:测试引用类型对象String
代码如下(示例):
Stopwatch t3 = new Stopwatch();
Stopwatch t4 = new Stopwatch();
t3.Start();
List<string> l1 = new List<string>();
for (int i = 0; i < n; i++)
{
l1.Add("X");//不发生装箱
string x = l1[i];//不发生拆箱
}
t3.Stop();
Console.WriteLine("List'time" + t3.ElapsedMilliseconds + "ms");
t4.Start();
ArrayList a1 = new ArrayList();
for (int i = 0; i < n; i++)
{
a1.Add("X");//不发生装箱
string x = (string)a1[i];//不发生拆箱
}
t4.Stop();
Console.WriteLine("ArrayList'time" + t4.ElapsedMilliseconds + "ms");
(示例运行结果):
List'time120ms
ArrayList'time1132ms
List'time106ms
ArrayList'time115ms
总结
List和ArrayList的区别
1、list性能较高,ArrayList性能较低
2、list一次存储中只能存储泛型中的类型,ArrayList在一次存储中任何类型的数据;
3、List中获取值取出的是泛型中发的类型,因为ArrayList对元素没有限制,系统会将中获取的值当object类型的数据,如果想获取到其中的内容需要进行;
4、List在使用时候需要导入的using指令为using System.Collections.Generic;
ArrayList在使用的时候需要导入的using指令为using System.Collections;
5、List属于泛型集合 ArrayList属于非泛型集合。
泛型数组List有两个优势:
1、对于存储值类型数据,性能更优
2、使得代码更加清晰,保证类型安全