深度复制: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,实现了深度复制。

相关推荐
泛凡(Linyongui)16 小时前
基于 CW32L010 的智能厨卫调温旋钮方案--低成本 EC21 编码旋钮全解析
单片机·嵌入式硬件·c#
暴走约伯18 小时前
【VFX工具链源码拆解 02】告别机械劳动(上):一键统改百个子粒子颜色与批量重命名
3d·unity·c#·材质
信息安全失业大专人员19 小时前
每日了解一个智能体-WorkBuddy
开发语言·ai·c#·智能体
呆呆敲代码的小Y20 小时前
【实战精选面试题】C# 面试题详细解答,按难易程度排序
android·java·游戏·c#·游戏开发·unity面试题·c#面试题
淡海水20 小时前
09-01-内存-Unity资源生命周期全景
unity·c#·游戏引擎·.netcore·gc
椒颜皮皮虾྅1 天前
让 C# 读懂整张图:DeploySharp 驱动 PaddleOCR v4/v5/v6,打通 OCR 全流程
开发语言·人工智能·深度学习·学习·c#·ocr·cuda
昂好的day1 天前
C# 同步异步与多线程:Thread / Task / 线程池一次讲透(上篇)
开发语言·windows·c#
吃一碗粉只付一碗钱1 天前
12-给SPA友好的401和403响应
c#·状态模式
caimouse2 天前
MonoDevelop 编译用户应用程序时调用的是哪个编译器
c#
will_net2 天前
apollo 站点部署&C#接入
开发语言·c#·apollo