如何在.NET中克隆字典? [英] How do you clone a dictionary in .NET?
问题描述
我知道我们应该使用字典而不是哈希表。我找不到克隆字典的方法。即使将它强制转换为ICollection以获取SyncRoot,我也不知道。
I know that we should rather be using dictionaries as opposed to hashtables. I cannot find a way to clone the dictionary though. Even if casting it to ICollection which I do to get the SyncRoot, which I know is also frowned upon.
我现在正忙着更改它。我是在正确的假设下,无法以通用方式实现任何类型的克隆,这就是为什么字典不支持克隆的原因?
I am busy changing that now. Am I under the correct assumption that there is no way to implement any sort of cloning in a generic way which is why clone is not supported for dictionary?
推荐答案
使用带字典的构造函数。参见以下示例
Use the Constructor that takes a Dictionary. See this example
var dict = new Dictionary<string, string>();
dict.Add("SO", "StackOverflow");
var secondDict = new Dictionary<string, string>(dict);
dict = null;
Console.WriteLine(secondDict["SO"]);
而且只是为了好玩。您可以使用LINQ!
And just for fun.. You can use LINQ! Which is a bit more Generic approach.
var secondDict = (from x in dict
select x).ToDictionary(x => x.Key, x => x.Value);
编辑
这对引用类型应该很好用,我尝试了以下操作:
This should work well with Reference Types, I tried the following:
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。
Which outputs "Filip Ekberg".
这篇关于如何在.NET中克隆字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!