装箱拆箱

3745人阅读 2021/5/23 13:45 总访问:676740 评论:0 收藏:0 手机
分类: Csharp

前言


C#装箱是将
值类型转换为引用类型;拆箱是将引用类型转换为值类型。

只有被装过箱的对象才能被拆箱

装箱

        //利用装箱和拆箱功能,可通过允许值类型的任何值与Object 类型的值相互转换,将值类型与引用类型链接起来。例如
            //装箱
            int a = 10;
            object obj = a;

拆箱

            
            int a = 10;
            object obj = a;
            //拆箱
           int b = (int)obj;

写个代码,看看进行了几次装拆箱!
int i=0;
System.Object obj=i;
Console.WriteLine(i+","+(int)obj);

其中共发生了3次装箱和一次拆箱!
第一次是将i装箱,第2次是输出的时候将i转换成string类型,而string类型为引用类型,即又是装箱,第三次装箱就是(int)obj的转换成string类型,装箱!
拆箱就是(int)obj,将obj拆箱!!

评价
脚踏实地,一步一个脚印
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术