装箱:将值类型转换为引用类型。
拆箱:将引用类型转换为值类型。
条件:看两种类型是否发生了装箱或者拆箱,要看,这两种类型是否存在继承关系。
using System;using System.Collections;using System.Collections.Generic;using System.Diagnostics;namespace _075_装箱和拆箱{class Program{static void Main(string[] args){int n = 1;object o = n;//装箱(值类型->引用类型)int nn = (int)o;//拆箱(引用类型->值类型)ArrayList list = new ArrayList();//计时Stopwatch sw = new Stopwatch();sw.Start();//这个循环完成了一千万次装箱操作for (int i = 0; i < 10000000; i++){list.Add(i);}sw.Stop();Console.WriteLine(sw.Elapsed);//00:00:01.2557403List<int> list1 = new List<int>();//计时Stopwatch sw1 = new Stopwatch();sw1.Start();//这个循环完成了一千万次赋值操作for (int i = 0; i < 10000000; i++){list1.Add(i);}sw1.Stop();Console.WriteLine(sw1.Elapsed);//00:00:00.0940650//可见,装箱操作时间较长//这个地方并没有发生任何的装箱或者拆箱(int string 无继承关系)string str = "123";int n1 = Convert.ToInt32(str);int n2 = 1;IComparable I = n2;//装箱,IComparable是int的一个接口Console.ReadKey();}}}
