c# list集合克隆
在C#中,List集合是一种泛型集合,可以存储任何类型的对象。克隆一个List集合可以通过以下几种方式实现:
- 使用List的构造函数
使用List的构造函数可以创建一个新的List对象,并将原始List中的元素复制到新List中。例如:
1 2 | List< int > list1 = new List< int > { 1, 2, 3 }; List< int > list2 = new List< int >(list1); |
在上面的代码中,list2
是一个新的List对象,它使用list1
中的元素进行初始化。
- 使用List的
CopyTo
方法
List的CopyTo
方法可以将原始List中的元素复制到一个数组中,然后再将数组中的元素复制到新的List中。例如
1 2 3 | List< int > list1 = new List< int > { 1, 2, 3 }; List< int > list2 = new List< int >(); list1.CopyTo(list2.ToArray()); |
在上面的代码中,list2
是一个新的List对象,它使用list1
中的元素进行初始化。
- 使用序列化
另一种克隆List集合的方法是通过序列化和反序列化。可以将原始List对象序列化为一个字节数组,然后再将字节数组反序列化为新的List对象。例如:
1 2 3 4 5 6 7 8 | List< int > list1 = new List< int > { 1, 2, 3 }; using (MemoryStream stream = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, list1); stream.Position = 0; List< int > list2 = (List< int >)formatter.Deserialize(stream); } |
在上面的代码中,list2
是一个新的List对象,它使用list1
中的元素进行初始化。这种方法可以用于任何类型的对象,但它需要更多的计算资源和时间。
C# List引用类型克隆的3种方法
# List引用类型克隆的3种方法,包括反射、序列化(依赖Newtonsoft.Json) 以及序列化(BinaryFormatter)的实现方法。
一、反射
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | /// <summary> /// 通过反射方式进行克隆 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <returns></returns> public static List<T> CloneReflect<T>( this List<T> list) where T : new () { List<T> items = new List<T>(); foreach ( var m in list) { var model = new T(); var ps = model.GetType().GetProperties(); var properties = m.GetType().GetProperties(); foreach ( var p in properties) { foreach ( var pm in ps) { if (pm.Name == p.Name) { pm.SetValue(model, p.GetValue(m)); } } } items.Add(model); } return items; } |
二、序列化(依赖Newtonsoft.Json)
1 2 3 4 5 6 7 8 9 10 11 | /// <summary> /// 采用第三方序列化方式克隆-依赖Newtonsoft.Json /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <returns></returns> public static List<T> CloneNJson<T>( this List<T> list) where T : new () { var str = JsonConvert.SerializeObject(list); return JsonConvert.DeserializeObject<List<T>>(str); } |
三、序列化(BinaryFormatter)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | /// <summary> /// 通过系统自带系列化克隆 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <returns></returns> public static List<T> CloneBF<T>( this List<T> list) { using (Stream objectStream = new MemoryStream()) { IFormatter formatter = new BinaryFormatter(); formatter.Serialize(objectStream, list); objectStream.Seek(0, SeekOrigin.Begin); return (List<T>)formatter.Deserialize(objectStream); } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 上周热点回顾(2.17-2.23)
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)