当前位置: 代码网 > it编程>编程语言>C# > C# 中 List 与 List 多层嵌套不改变原值的实现方法(深度复制)

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

2024年05月19日 C# 我要评论
概述:以上内容详细介绍了在 c# 中实现不改变原 list 值的多层嵌套复制方法,包括使用 automapper、json.net、以及对象序列化的步骤和示例。这些方法提供了灵活而高效的方式,可以根据

概述:以上内容详细介绍了在 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 多层嵌套内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com