当前位置:首页 > 科技  > 软件

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

来源: 责编: 时间:2024-05-23 17:13:38 208观看
导读概述:以下内容详细介绍了在 C# 中实现不改变原 List 值的多层嵌套复制方法,包括使用 AutoMapper、Json.NET、以及对象序列化的步骤和示例。这些方法提供了灵活而高效的方式,可以根据项目需求选择最适合的深度复制方式。1

sDJ28资讯网——每日最新资讯28at.com

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

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

AutoMapper 是一个对象映射工具,可以方便地进行对象之间的映射。以下是使用 AutoMapper 实现多层嵌套复制的步骤和示例:sDJ28资讯网——每日最新资讯28at.com

首先,你需要在项目中安装 AutoMapper 包。你可以通过 NuGet 包管理器控制台运行以下命令来安装:sDJ28资讯网——每日最新资讯28at.com

Install-Package AutoMapper

然后,你可以使用以下代码进行深度复制:sDJ28资讯网——每日最新资讯28at.com

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 配置,然后创建映射器,并使用映射器进行深度复制。sDJ28资讯网——每日最新资讯28at.com

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

Json.NET(Newtonsoft.Json)是一个用于处理 JSON 数据的强大库,也可以用于实现深度复制。以下是使用 Json.NET 实现多层嵌套复制的步骤和示例:sDJ28资讯网——每日最新资讯28at.com

首先,你需要在项目中安装 Json.NET 包。你可以通过 NuGet 包管理器控制台运行以下命令来安装:sDJ28资讯网——每日最新资讯28at.com

Install-Package Newtonsoft.Json

然后,你可以使用以下代码进行深度复制:sDJ28资讯网——每日最新资讯28at.com

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,实现了深度复制。sDJ28资讯网——每日最新资讯28at.com

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

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

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,实现了深度复制。sDJ28资讯网——每日最新资讯28at.com

本文链接:http://www.28at.com/showinfo-26-90351-0.html深度复制:C# 中 List 与 List 多层嵌套不改变原值的实现方法

声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。邮件:2376512515@qq.com

上一篇: 如何用Python轻松检测文本相似性:原理与方法

下一篇: Tailwind 4.0 即将发布,看起来很不错!

标签:
  • 热门焦点
  • 6月安卓手机好评榜:魅族20 Pro蝉联冠军

    性能榜和性价比榜之后,我们来看最后的安卓手机好评榜,数据来源安兔兔评测,收集时间2023年6月1日至6月30日,仅限国内市场。第一名:魅族20 Pro好评率:95%5月份的时候魅族20 Pro就是
  • 只需五步,使用start.spring.io快速入门Spring编程

    步骤1打开https://start.spring.io/,按照屏幕截图中的内容创建项目,添加 Spring Web 依赖项,并单击“生成”按钮下载 .zip 文件,为下一步做准备。请在进入步骤2之前进行解压。图
  • 破圈是B站头上的紧箍咒

    来源 | 光子星球撰文 | 吴坤谚编辑 | 吴先之每年的暑期档都少不了瞄准追剧女孩们的古偶剧集,2021年有优酷的《山河令》,2022年有爱奇艺的《苍兰诀》,今年却轮到小破站抓住了追
  • 中国家电海外掘金正当时|出海专题

    作者|吴南南编辑|胡展嘉运营|陈佳慧出品|零态LT(ID:LingTai_LT)2023年,出海市场战况空前,中国创业者在海外纷纷摩拳擦掌,以期能够把中国的商业模式、创业理念、战略打法输出海外,他们依
  • 网红炒股不为了赚钱,那就是耍流氓!

    来源:首席商业评论6月26日高调宣布入市,网络名嘴大v胡锡进居然进军了股市。在一次财经媒体峰会上,几个财经圈媒体大佬就&ldquo;胡锡进炒股是否知道认真报道&rdquo;展开讨论。有
  • 微博大门常打开,迎接海外画师漂洋东渡

    作者:互联网那些事&ldquo;起猛了,我能看得懂日语了&rdquo;。&ldquo;为什么日本人说话我能听懂?&rdquo;&ldquo;中文不像中文,日语不像日语,但是我竟然看懂了&rdquo;&hellip;&hell
  • 华为开发者大会2023日程公开:开设鸿蒙HarmonyOS 4体验区

    IT之家 7 月 31 日消息,华为今日公布了 HDC.Together 开发者大会 2023 的详细日程。整场大会将于 8 月 4 日-6 日之间举行,届时将发布最新一代鸿蒙 H
  • iQOO 11S新品发布会

    iQOO将在7月4日19:00举行新品发布会,推出杭州亚运会电竞赛事官方用机iQOO 11S。
  • iQOO Neo8 Pro即将开售:到手价3099元起 安卓性能最强旗舰

    5月23日,iQOO如期举行了新品发布会,全新的iQOO Neo8系列也正式与大家见面,包含iQOO Neo8和iQOO Neo8 Pro两个版本,其中标准版搭载高通骁龙8+,而Pro版更
Top