1、装箱就是将值类型转换为引用类型(object类型是一切类型的父类,根据里式转换法可以接受任意类型的数据,当然也可以强制转换为其他类型)
2、拆箱就是将引用类型转换为值类型
*在代码中尽量减少装箱和拆箱,一旦有装箱和拆箱就会影响运行时间
**看两种类型是否发生了装箱和拆箱,要看这两种类型是否有继承关系;如果没有继承关系例如:string 转换为int,他们没有继承关系,在内存上一个在栈中一个在堆中,内存没有交集不会发生拆装箱,有继承关系的在内存中才有可能没有有交集
string str = "123456";int num = Convert.ToInt32(str); 此处没有发生类型转换
1、拆装箱:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 拆箱和装箱 { class Program { static void Main(string[] args) { //object 是一切类的直接或间接父类 int m = 10; object obj = m;//装箱 int n = (int)obj;//拆箱 Console.WriteLine(obj); Console.WriteLine(n); Console.ReadKey(); } } }
运行结果:
分析调试:
2、拆装箱的性能分析:在代码中尽量减少装箱和拆箱,一旦有装箱和拆箱就会影响运行时间
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 拆装箱的性能分析 { class Program { static void Main(string[] args) { //涉及装箱操作 ArrayList list = new ArrayList(); //1000000次的装箱 Stopwatch sw1 = new Stopwatch(); sw1.Start(); for (int i = 0; i < 10000000; i++) { list.Add(i); } sw1.Stop(); Console.WriteLine("10000000次装箱操作所用的时间: "+ sw1.Elapsed); Console.WriteLine("======分割线======"); //没有涉及装箱的操作 List<int> listint = new List<int>(); Stopwatch sw2 = new Stopwatch(); //10000000次没有涉及到装箱的操作 sw2.Start(); for (int i = 0; i < 10000000; i++) { listint.Add(i); } sw2.Stop(); Console.WriteLine("10000000没有装箱的操作所用的时间: "+ sw2.Elapsed); Console.ReadKey(); } } }
运行结果: