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

 更新时间:2024年03月04日 09:23:13   作者:架构师老卢  
这篇文章主要介绍了C# 中 List 与 List 多层嵌套不改变原值的实现方法,使用 BinaryFormatter 将原始 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 多层嵌套不改变原值的实现方法的文章就介绍到这了,更多相关C#  List 多层嵌套内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 递归案例分享

    递归案例分享

    一般定义:程序调用自身的编程技巧称为递归( recursion)。
    2014-05-05
  • WPF实现在线预览和显示Word和PDF文件

    WPF实现在线预览和显示Word和PDF文件

    这篇文章主要为大家详细介绍了如何使用WPF实现在线预览和显示Word和PDF文件,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2024-02-02
  • DevExpress实现GridControl显示Gif动画的方法

    DevExpress实现GridControl显示Gif动画的方法

    这篇文章主要介绍了DevExpress实现GridControl显示Gif动画的方法,这是比较实用的方法,需要的朋友可以参考下
    2014-08-08
  • 如何搭建新的WPF项目框架

    如何搭建新的WPF项目框架

    这篇文章主要介绍了如何搭建新的WPF项目框架,在项目开发中比较常见的开发模式就是MVVM模式,使用MVVM框架开发好处:1、框架较轻,2、学习成本低、3、适用大多数中小型项目,4、相对于微软的prism框架更容易上手,需要的朋友可以参考下
    2015-07-07
  • C#多线程编程详解

    C#多线程编程详解

    C#提供了丰富的多线程操作,为编程带来了极大的便利,但如果使用不当也会带来各种各样的麻烦。本篇文章主要介绍了C#多线程,有需要的可以了解一下。
    2016-11-11
  • C#强制类型转换小结

    C#强制类型转换小结

    任何一门编程语言均有相关数据类型。C#也不例外,不过转换过程要注意小类型能转换成大类型,但大类型一般不能转换成小类型,下面小编给大家详解C#强制类型转换小结,需要的朋友参考下吧
    2017-07-07
  • C#中获取数据的方法实例

    C#中获取数据的方法实例

    这篇文章主要给大家介绍了关于C#中获取数据的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • 关于C#中async/await的用法实例详解

    关于C#中async/await的用法实例详解

    这篇文章主要介绍了关于C#中async/await的用法,今天写一个demo彻底搞明白async/await的用法,代码简单易懂,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-02-02
  • C#实现GZip压缩和解压缩入门实例

    C#实现GZip压缩和解压缩入门实例

    C#中用GZip对数据压缩和解压缩非常方便,但是当我第一次拿到这个类的时候却感觉很迷茫,无从下手
    2014-04-04
  • C# WPF ListBox 动态显示图片功能

    C# WPF ListBox 动态显示图片功能

    这篇文章主要介绍了C# WPF ListBox 动态显示图片,处理过程分为前台代码和后台代码,本文结合实例代码给大家介绍的非常详细,需要的朋友可以参考下
    2023-08-08

最新评论