我知道我们应该使用字典而不是哈希表。但我找不到克隆字典的方法。即使将其转换为 ICollection(我这样做是为了获取 SyncRoot),我知道这也是不受欢迎的。
我现在正忙着改变它。我是否有正确的假设,即无法以通用方式实现任何类型的克隆,这就是字典不支持克隆的原因?
最佳答案
使用接受字典的构造函数。请参阅此示例
var dict = new Dictionary<string, string>();
dict.Add("SO", "StackOverflow");
var secondDict = new Dictionary<string, string>(dict);
dict = null;
Console.WriteLine(secondDict["SO"]);
只是为了好玩..您可以使用 LINQ!这是更通用的方法。
var secondDict = (from x in dict
select x).ToDictionary(x => x.Key, x => x.Value);
编辑
这应该适用于引用类型,我尝试了以下方法:
internal class User
{
public int Id { get; set; }
public string Name { get; set; }
public User Parent { get; set; }
}
以及上面修改后的代码
var dict = new Dictionary<string, User>();
dict.Add("First", new User
{ Id = 1, Name = "Filip Ekberg", Parent = null });
dict.Add("Second", new User
{ Id = 2, Name = "Test test", Parent = dict["First"] });
var secondDict = (from x in dict
select x).ToDictionary(x => x.Key, x => x.Value);
dict.Clear();
dict = null;
Console.WriteLine(secondDict["First"].Name);
输出“Filip Ekberg”。
关于.net - 如何在 .NET 中克隆字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2279619/