装箱与拆箱

  装箱:就是将值类型转换为引用类型。
  拆箱:将引用类型转换为值类型。

  看两种类型是否发生了装箱或者拆箱,要看,这两种类型是否存在继承关系。

            //int n = 10;
            //object o = n;//装箱
            //int nn = (int)o;//拆箱

            int n = 10;
            IComparable i = n;//装箱
            //这个地方没有发生任意类型的装箱或者拆箱
            //string str = "123";
            //int n = Convert.ToInt32(str);

    装箱和拆箱会影响系统性能,如果次数太多的话,进行引用类型和值类型之间的转换会消耗不少时间。所以在程序中,我们应当尽量避免装箱和拆箱的操作。

            ArrayList list = new ArrayList();
            //List<int> list = new List<int>();
            //这个循环发生了100万次装箱操作
            Stopwatch sw = new Stopwatch();

            //向ArrayList中添加数据  00:00:02.4370587
            //向List中添加数据          00:00:00.2857600
            sw.Start();
            for (int i = 0; i < 10000000; i++)
            {
                list.Add(i);
            }
            sw.Stop();
            Console.WriteLine(sw.Elapsed);
            Console.ReadKey();

    由上面的代码我们可以看到,向ArrayList中添加数据的时候,每次都要进行装箱操作。这样增加了程序运行的时间。

  

原文地址:https://www.cnblogs.com/lcxBlog/p/4884573.html