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

本文主要是介绍深度复制:C# 中 List 与 List 多层嵌套不改变原值的实现方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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

1. 使用 AutoMapper 进行多层嵌套复制

AutoMapper 是一个对象映射工具,可以方便地进行对象之间的映射。以下是使用 AutoMapper 实现多层嵌套复制的步骤和示例:

首先,你需要在项目中安装 AutoMapper 包。你可以通过 NuGet 包管理器控制台运行以下命令来安装:

Install-Package AutoMapper

然后,你可以使用以下代码进行深度复制:

using AutoMapper;
using System;
using System.Collections.Generic;class Person
{public string Name { get; set; }public int Age { get; set; }
}class Student
{public string StudentId { get; set; }public Person Info { get; set; }
}class Program
{static void Main(){// 创建原始 List,多层嵌套List<Student> originalList = new List<Student>{new Student { StudentId = "001", Info = new Person { Name = "Alice", Age = 25 } },new Student { StudentId = "002", Info = new Person { Name = "Bob", Age = 30 } }};// 使用 AutoMapper 实现深度复制List<Student> copiedList = DeepCopyWithAutoMapper(originalList);// 修改复制后的值copiedList[0].Info.Name = "Charlie";// 打印原始值,验证原始 List 的值是否改变Console.WriteLine("原始 List 的值:");PrintList(originalList);// 打印复制后的值Console.WriteLine("\n复制后 List 的值:");PrintList(copiedList);}static List<Student> DeepCopyWithAutoMapper(List<Student> originalList){// 初始化 AutoMapper 配置var config = new MapperConfiguration(cfg =>{// 针对每一层嵌套的类型进行映射配置cfg.CreateMap<Student, Student>();cfg.CreateMap<Person, Person>();});// 创建映射器IMapper mapper = config.CreateMapper();// 使用映射器进行深度复制List<Student> newList = mapper.Map<List<Student>>(originalList);return newList;}// 打印 List 的方法static void PrintList(List<Student> list){foreach (var student in list){Console.WriteLine($"StudentId: {student.StudentId}, Name: {student.Info.Name}, Age: {student.Info.Age}");}}
}

在这个示例中,首先初始化 AutoMapper 配置,然后创建映射器,并使用映射器进行深度复制。

2. 使用 Json.NET 进行多层嵌套复制

Json.NET(Newtonsoft.Json)是一个用于处理 JSON 数据的强大库,也可以用于实现深度复制。以下是使用 Json.NET 实现多层嵌套复制的步骤和示例:

首先,你需要在项目中安装 Json.NET 包。你可以通过 NuGet 包管理器控制台运行以下命令来安装:

Install-Package Newtonsoft.Json

然后,你可以使用以下代码进行深度复制:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;class Person
{public string Name { get; set; }public int Age { get; set; }
}class Student
{public string StudentId { get; set; }public Person Info { get; set; }
}class Program
{static void Main(){// 创建原始 List,多层嵌套List<Student> originalList = new List<Student>{new Student { StudentId = "001", Info = new Person { Name = "Alice", Age = 25 } },new Student { StudentId = "002", Info = new Person { Name = "Bob", Age = 30 } }};// 使用 Json.NET 实现深度复制List<Student> copiedList = DeepCopyWithJson(originalList);// 修改复制后的值copiedList[0].Info.Name = "Charlie";// 打印原始值,验证原始 List 的值是否改变Console.WriteLine("原始 List 的值:");PrintList(originalList);// 打印复制后的值Console.WriteLine("\n复制后 List 的值:");PrintList(copiedList);}static List<Student> DeepCopyWithJson(List<Student> originalList){// 使用 JsonConvert 进行深度复制string json = JsonConvert.SerializeObject(originalList);List<Student> newList = JsonConvert.DeserializeObject<List<Student>>(json);return newList;}// 打印 List 的方法static void PrintList(List<Student> list){foreach(var student in list){Console.WriteLine($"StudentId: {student.StudentId}, Name: {student.Info.Name}, Age: {student.Info.Age}");}}
}

在这个示例中,使用 JsonConvert 将原始 List 转换为 JSON 字符串,然后再从 JSON 字符串中反序列化得到新的 List,实现了深度复制。

3. 使用对象序列化和反序列化进行深度复制

另一种常见的方法是使用 C# 的对象序列化和反序列化功能,将对象序列化为字节流,然后再反序列化为新的对象。以下是使用序列化和反序列化实现多层嵌套复制的步骤和示例:

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;class Person
{public string Name { get; set; }public int Age { get; set; }
}class Student
{public string StudentId { get; set; }public Person Info { get; set; }
}class Program
{static void Main(){// 创建原始 List,多层嵌套List<Student> originalList = new List<Student>{new Student { StudentId = "001", Info = new Person { Name = "Alice", Age = 25 } },new Student { StudentId = "002", Info = new Person { Name = "Bob", Age = 30 } }};// 使用序列化和反序列化实现深度复制List<Student> copiedList = DeepCopyWithSerialization(originalList);// 修改复制后的值copiedList[0].Info.Name = "Charlie";// 打印原始值,验证原始 List 的值是否改变Console.WriteLine("原始 List 的值:");PrintList(originalList);// 打印复制后的值Console.WriteLine("\n复制后 List 的值:");PrintList(copiedList);}static List<Student> DeepCopyWithSerialization(List<Student> originalList){IFormatter formatter = new BinaryFormatter();using (MemoryStream stream = new MemoryStream()){formatter.Serialize(stream, originalList);stream.Seek(0, SeekOrigin.Begin);return (List<Student>)formatter.Deserialize(stream);}}// 打印 List 的方法static void PrintList(List<Student> list){foreach (var student in list){Console.WriteLine($"StudentId: {student.StudentId}, Name: {student.Info.Name}, Age: {student.Info.Age}");}}
}

在这个示例中,使用 BinaryFormatter 将原始 List 序列化为字节流,然后再反序列化得到新的 List,实现了深度复制。

这篇关于深度复制:C# 中 List 与 List 多层嵌套不改变原值的实现方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/805163

相关文章

python使用Akshare与Streamlit实现股票估值分析教程(图文代码)

《python使用Akshare与Streamlit实现股票估值分析教程(图文代码)》入职测试中的一道题,要求:从Akshare下载某一个股票近十年的财务报表包括,资产负债表,利润表,现金流量表,保存... 目录一、前言二、核心知识点梳理1、Akshare数据获取2、Pandas数据处理3、Matplotl

分布式锁在Spring Boot应用中的实现过程

《分布式锁在SpringBoot应用中的实现过程》文章介绍在SpringBoot中通过自定义Lock注解、LockAspect切面和RedisLockUtils工具类实现分布式锁,确保多实例并发操作... 目录Lock注解LockASPect切面RedisLockUtils工具类总结在现代微服务架构中,分布

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

Python安装Pandas库的两种方法

《Python安装Pandas库的两种方法》本文介绍了三种安装PythonPandas库的方法,通过cmd命令行安装并解决版本冲突,手动下载whl文件安装,更换国内镜像源加速下载,最后建议用pipli... 目录方法一:cmd命令行执行pip install pandas方法二:找到pandas下载库,然后

Redis客户端连接机制的实现方案

《Redis客户端连接机制的实现方案》本文主要介绍了Redis客户端连接机制的实现方案,包括事件驱动模型、非阻塞I/O处理、连接池应用及配置优化,具有一定的参考价值,感兴趣的可以了解一下... 目录1. Redis连接模型概述2. 连接建立过程详解2.1 连php接初始化流程2.2 关键配置参数3. 最大连

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买

python设置环境变量路径实现过程

《python设置环境变量路径实现过程》本文介绍设置Python路径的多种方法:临时设置(Windows用`set`,Linux/macOS用`export`)、永久设置(系统属性或shell配置文件... 目录设置python路径的方法临时设置环境变量(适用于当前会话)永久设置环境变量(Windows系统

深度解析Nginx日志分析与499状态码问题解决

《深度解析Nginx日志分析与499状态码问题解决》在Web服务器运维和性能优化过程中,Nginx日志是排查问题的重要依据,本文将围绕Nginx日志分析、499状态码的成因、排查方法及解决方案展开讨论... 目录前言1. Nginx日志基础1.1 Nginx日志存放位置1.2 Nginx日志格式2. 499