C# 字典Dictionary 深拷贝方法

C# 的字典暂时不支持默认的Clone方法,网上的不少字典Dictionary克隆方法大多是浅拷贝方法,例如:

 1 /// <summary>
 2 ///  需要修改的文件信息,用于 分布式提取数据
 3 /// </summary>
 4 public class ChangeScriptInformation
 5 {
 6     public string fileName;           // 要修改的 文件名
 7     public string changeFindString;   // 需要修改的文件内容
 8     public string changeAttribute;    // 修改属性(如何修改)
 9     public string changeResultString; // 对应的修改结果
10 }
11 Dictionary<string, List<ChangeScriptInformation>> changeScriptInfo = new Dictionary<string, List<ChangeScriptInformation>>();  // 需要修改的文件信息,用于 分布式提取数据
12 for (int i = 0; i < controlScript.Length; i++)
13 {
14     if (!changeScriptInfo.ContainsKey(controlScript[i]))
15     {
16         List<ChangeScriptInformation> listChangeScriptInfo = new List<ChangeScriptInformation>();
17         changeScriptInfo.Add(controlScript[i], listChangeScriptInfo);
18     }
19     ChangeScriptInformation change = new ChangeScriptInformation();
20     change.fileName = controlScript[i];
21     change.changeFindString = controlScriptFileFind[i];
22     change.changeAttribute = controlAttribute[i];
23     changeScriptInfo[controlScript[i]].Add(change);
24 }
25 
26 serversInformation[targetServer[i].ToString()].changeScriptInformation = new Dictionary<string, List<ChangeScriptInformation>>(changeScriptInfo);  // 浅拷贝
27 serversInformation[targetServer[i].ToString()].changeScriptInformation = changeScriptInfo.ToDictionary(entry => entry.Key, entry => entry.Value);  // 浅拷贝

这样的方法只能完成对字典 Dictionary<string, List<ChangeScriptInformation>> changeScriptInfo 的浅拷贝,网上推荐的深拷贝方法多是使用反射或序列化来实现的,根据相关资料,这样的深拷贝方式十分影响程序的执行,如果需要提高效率,可以借助C#对象映射器来实现,比如:AutoMapper 和 Mapster,本文重点介绍使用 Mapster 进行字典深拷贝的操作方法:

1. 在VS NuGet软件包管理器中,搜索并安装 Mapster,注意针对 .NET Framework 4.7.2,需要安装 Mapster 7.3.0,7.4.0不兼容。

 2. Mapster安装完毕后,在代码页面要声明引用,如下:

1 using Mapster;  // 对象映射器

 3. 使用如下方式实现上述案例的深拷贝:

字典1=字典2.Adapt<字典2结构>();

1 serversInformation[targetServer[i].ToString()].changeScriptInformation = changeScriptInfo.Adapt<Dictionary<string, List<ChangeScriptInformation>>>();   // 使用对象映射器进行 深拷贝

 

 

参考资料:

c#实现深拷贝的几种方式及效率对比_automapper 深拷贝_EverestVIP的博客-CSDN博客

C# Mapster 对象映射器(C#对象映射器) - 一颗花生豆 - 博客园 (cnblogs.com)

posted @ 2023-10-25 17:14  CollinsLi  阅读(827)  评论(0编辑  收藏  举报