c#装箱和拆箱

1.装箱:将值类型转换为引用类型

2.拆箱:将引用类型转换为值类型

static void Main(string[] args)
        {

            int n = 10;//值类型
            object o = n;//将值类型赋值给引用类型,装箱
            int nn=(int)o;//将引用类型强转为值类型,拆箱
        }

装箱效率验证:

ArrayList arrayList = new ArrayList();
            //这个循环发生了10000000次装箱操作
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            for (int i = 0; i < 10000000; i++)
            {
                arrayList.Add(i);//装箱
            }
            stopwatch.Stop();
            Console.WriteLine(stopwatch.Elapsed.ToString());

输出结果:

 

 

static void Main(string[] args)
        {

            List<int> list = new List<int>();
            //这个循环没有发生任何拆装箱操作
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            for (int i = 0; i < 10000000; i++)
            {
                list.Add(i);
            }
            stopwatch.Stop();
            Console.WriteLine(stopwatch.Elapsed.ToString());
        }

输出结果:

 

 所以说,装箱会影响到系统的性能问题。

 

 

看两种类型是否发生了拆箱和装箱,要看这两种类型是否发生了继承关系,如果存在继承关系,则有可能发生,否则不可能发生拆装箱。

 

 

3.常见的值类型和引用类型:

值类型:int,double,bool,char,decimal,struct,enum

引用类型:string,自定义类,数组,集合,object,接口

4.存储方面:

值类型的值是存储在内存的栈当中

引用类型的值是存储在内存的堆中

 

posted @ 2022-09-21 15:37  ZerryLuo  阅读(107)  评论(0编辑  收藏  举报