翼度科技»论坛 编程开发 .net 查看内容

深度复制:C# 中 List 与 List 多层嵌套不改变原值的实现方法

7

主题

7

帖子

21

积分

新手上路

Rank: 1

积分
21
 
概述:以上内容详细介绍了在 C# 中实现不改变原 List 值的多层嵌套复制方法,包括使用 AutoMapper、Json.NET、以及对象序列化的步骤和示例。这些方法提供了灵活而高效的方式,可以根据项目需求选择最适合的深度复制方式。
1. 使用 AutoMapper 进行多层嵌套复制

AutoMapper 是一个对象映射工具,可以方便地进行对象之间的映射。以下是使用 AutoMapper 实现多层嵌套复制的步骤和示例:
首先,你需要在项目中安装 AutoMapper 包。你可以通过 NuGet 包管理器控制台运行以下命令来安装:
  1. Install-Package AutoMapper
复制代码
然后,你可以使用以下代码进行深度复制:
  1. using AutoMapper;
  2. using System;
  3. using System.Collections.Generic;
  4. class Person
  5. {
  6.     public string Name { get; set; }
  7.     public int Age { get; set; }
  8. }
  9. class Student
  10. {
  11.     public string StudentId { get; set; }
  12.     public Person Info { get; set; }
  13. }
  14. class Program
  15. {
  16.     static void Main()
  17.     {
  18.         // 创建原始 List,多层嵌套
  19.         List<Student> originalList = new List<Student>
  20.         {
  21.             new Student { StudentId = "001", Info = new Person { Name = "Alice", Age = 25 } },
  22.             new Student { StudentId = "002", Info = new Person { Name = "Bob", Age = 30 } }
  23.         };
  24.         // 使用 AutoMapper 实现深度复制
  25.         List<Student> copiedList = DeepCopyWithAutoMapper(originalList);
  26.         // 修改复制后的值
  27.         copiedList[0].Info.Name = "Charlie";
  28.         // 打印原始值,验证原始 List 的值是否改变
  29.         Console.WriteLine("原始 List 的值:");
  30.         PrintList(originalList);
  31.         // 打印复制后的值
  32.         Console.WriteLine("\n复制后 List 的值:");
  33.         PrintList(copiedList);
  34.     }
  35.     static List<Student> DeepCopyWithAutoMapper(List<Student> originalList)
  36.     {
  37.         // 初始化 AutoMapper 配置
  38.         var config = new MapperConfiguration(cfg =>
  39.         {
  40.             // 针对每一层嵌套的类型进行映射配置
  41.             cfg.CreateMap<Student, Student>();
  42.             cfg.CreateMap<Person, Person>();
  43.         });
  44.         // 创建映射器
  45.         IMapper mapper = config.CreateMapper();
  46.         // 使用映射器进行深度复制
  47.         List<Student> newList = mapper.Map<List<Student>>(originalList);
  48.         return newList;
  49.     }
  50.     // 打印 List 的方法
  51.     static void PrintList(List<Student> list)
  52.     {
  53.         foreach (var student in list)
  54.         {
  55.             Console.WriteLine($"StudentId: {student.StudentId}, Name: {student.Info.Name}, Age: {student.Info.Age}");
  56.         }
  57.     }
  58. }
复制代码
在这个示例中,首先初始化 AutoMapper 配置,然后创建映射器,并使用映射器进行深度复制。
2. 使用 Json.NET 进行多层嵌套复制

Json.NET(Newtonsoft.Json)是一个用于处理 JSON 数据的强大库,也可以用于实现深度复制。以下是使用 Json.NET 实现多层嵌套复制的步骤和示例:
首先,你需要在项目中安装 Json.NET 包。你可以通过 NuGet 包管理器控制台运行以下命令来安装:
  1. Install-Package Newtonsoft.Json
复制代码
然后,你可以使用以下代码进行深度复制:
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. class Person
  5. {
  6.     public string Name { get; set; }
  7.     public int Age { get; set; }
  8. }
  9. class Student
  10. {
  11.     public string StudentId { get; set; }
  12.     public Person Info { get; set; }
  13. }
  14. class Program
  15. {
  16.     static void Main()
  17.     {
  18.         // 创建原始 List,多层嵌套
  19.         List<Student> originalList = new List<Student>
  20.         {
  21.             new Student { StudentId = "001", Info = new Person { Name = "Alice", Age = 25 } },
  22.             new Student { StudentId = "002", Info = new Person { Name = "Bob", Age = 30 } }
  23.         };
  24.         // 使用 Json.NET 实现深度复制
  25.         List<Student> copiedList = DeepCopyWithJson(originalList);
  26.         // 修改复制后的值
  27.         copiedList[0].Info.Name = "Charlie";
  28.         // 打印原始值,验证原始 List 的值是否改变
  29.         Console.WriteLine("原始 List 的值:");
  30.         PrintList(originalList);
  31.         // 打印复制后的值
  32.         Console.WriteLine("\n复制后 List 的值:");
  33.         PrintList(copiedList);
  34.     }
  35.     static List<Student> DeepCopyWithJson(List<Student> originalList)
  36.     {
  37.         // 使用 JsonConvert 进行深度复制
  38.         string json = JsonConvert.SerializeObject(originalList);
  39.         List<Student> newList = JsonConvert.DeserializeObject<List<Student>>(json);
  40.         return newList;
  41.     }
  42.     // 打印 List 的方法
  43.     static void PrintList(List<Student> list)
  44.     {
  45.         foreach
  46. (var student in list)
  47.         {
  48.             Console.WriteLine($"StudentId: {student.StudentId}, Name: {student.Info.Name}, Age: {student.Info.Age}");
  49.         }
  50.     }
  51. }
复制代码
在这个示例中,使用 JsonConvert 将原始 List 转换为 JSON 字符串,然后再从 JSON 字符串中反序列化得到新的 List,实现了深度复制。
3. 使用对象序列化和反序列化进行深度复制

另一种常见的方法是使用 C# 的对象序列化和反序列化功能,将对象序列化为字节流,然后再反序列化为新的对象。以下是使用序列化和反序列化实现多层嵌套复制的步骤和示例:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Runtime.Serialization;
  5. using System.Runtime.Serialization.Formatters.Binary;
  6. class Person
  7. {
  8.     public string Name { get; set; }
  9.     public int Age { get; set; }
  10. }
  11. class Student
  12. {
  13.     public string StudentId { get; set; }
  14.     public Person Info { get; set; }
  15. }
  16. class Program
  17. {
  18.     static void Main()
  19.     {
  20.         // 创建原始 List,多层嵌套
  21.         List<Student> originalList = new List<Student>
  22.         {
  23.             new Student { StudentId = "001", Info = new Person { Name = "Alice", Age = 25 } },
  24.             new Student { StudentId = "002", Info = new Person { Name = "Bob", Age = 30 } }
  25.         };
  26.         // 使用序列化和反序列化实现深度复制
  27.         List<Student> copiedList = DeepCopyWithSerialization(originalList);
  28.         // 修改复制后的值
  29.         copiedList[0].Info.Name = "Charlie";
  30.         // 打印原始值,验证原始 List 的值是否改变
  31.         Console.WriteLine("原始 List 的值:");
  32.         PrintList(originalList);
  33.         // 打印复制后的值
  34.         Console.WriteLine("\n复制后 List 的值:");
  35.         PrintList(copiedList);
  36.     }
  37.     static List<Student> DeepCopyWithSerialization(List<Student> originalList)
  38.     {
  39.         IFormatter formatter = new BinaryFormatter();
  40.         using (MemoryStream stream = new MemoryStream())
  41.         {
  42.             formatter.Serialize(stream, originalList);
  43.             stream.Seek(0, SeekOrigin.Begin);
  44.             return (List<Student>)formatter.Deserialize(stream);
  45.         }
  46.     }
  47.     // 打印 List 的方法
  48.     static void PrintList(List<Student> list)
  49.     {
  50.         foreach (var student in list)
  51.         {
  52.             Console.WriteLine($"StudentId: {student.StudentId}, Name: {student.Info.Name}, Age: {student.Info.Age}");
  53.         }
  54.     }
  55. }
复制代码
在这个示例中,使用 BinaryFormatter 将原始 List 序列化为字节流,然后再反序列化得到新的 List,实现了深度复制。
 



来源:https://www.cnblogs.com/hanbing81868164/p/18051098
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具