c#,装箱拆箱知识点示例理解
c#专栏记录:
内容
c#,装箱拆箱知识点示例理解
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;namespace ConsoleApp2
{public class MyClass{public int Value { get; set; } = 10;}public class Program:MyClass // 继承{public static Program Myclass__ = new Program();static void Main(string[] args){Console.WriteLine("Hello World!");/* 1、集合操作 */ArrayList list = new ArrayList();list.Add(42);//int装箱为objectlist.Add(3.14);//double装箱为objectlist.Add(true);//bool装箱为objectint value = (int)list[0];var value_ = list[2];Console.WriteLine(value);Console.WriteLine(value_);/* 2、object类型参数传递 */int i = 123;object obj = i;//int装箱为object,是引用类型,会在堆上分配新的内存Console.WriteLine(obj);//obj数值为·123i = 456;Console.WriteLine(obj);//obj的值没有改变 123Console.WriteLine(i);//`i`的值改变为456/* 装箱类型判断 */if (obj is int)Console.WriteLine("is int");elseConsole.WriteLine("is not int");if (list[2] is bool)Console.WriteLine("is bool");elseConsole.WriteLine("is not bool");/* 3、格式化字符串 装箱 */int number = 42;string result = string.Format("The number is {0}", number);//装箱/* 4、反射操作 装箱 *///通过反射设置值类型属性时会发生装箱var property = typeof(MyClass).GetProperty("Value");property.SetValue(Myclass__, 88);//装箱 int 88装箱为objectConsole.WriteLine(Myclass__.Value);/* (1)、不要频繁装箱、拆箱。 好的方法,使用泛型集合 */List<int> list1 = new List<int>();for (int z=0; z < 1000; z++){list1.Add(z);}// 不好的做法 - 频繁装箱拆箱ArrayList list2 = new ArrayList();for (int y = 0; y < 1000; y++){list.Add(y); // 每次循环都装箱}Console.WriteLine(list2[0]);}}
}
总结
阿巴阿巴,阿巴阿巴
致谢
靠咖啡续命的牛马,👍点赞 📁 关注 💬评论 💰打赏。
参考
[1] deepseek等ai
往期回顾
- 无,新手上车