如何在.NET中克隆字典?

我知道我们宁愿使用字典而不使用哈希表。 我找不到克隆字典的方法。 即使将它投射到ICollection上,我也会得到SyncRoot,我知道这也是令人不悦的。

现在我正忙于改变这一点。 我是否有正确的假设,没有办法以通用的方式实现任何types的克隆,这就是为什么字典不支持克隆?

使用带有字典的构造函数。 看到这个例子

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); 

编辑

这应该适用于引用types,我尝试了以下内容:

 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”。

这是我曾经写过的一个快速和肮脏的克隆方法…我想最初的想法是从CodeProject。

 Imports System.Runtime.Serialization Imports System.Runtime.Serialization.Formatters.Binary Public Shared Function Clone(Of T)(ByVal inputObj As T) As T 'creating a Memorystream which works like a temporary storeage ' Using memStrm As New MemoryStream() 'Binary Formatter for serializing the object into memory stream ' Dim binFormatter As New BinaryFormatter(Nothing, New StreamingContext(StreamingContextStates.Clone)) 'talks for itself ' binFormatter.Serialize(memStrm, inputObj) 'setting the memorystream to the start of it ' memStrm.Seek(0, SeekOrigin.Begin) 'try to cast the serialized item into our Item ' Try return DirectCast(binFormatter.Deserialize(memStrm), T) Catch ex As Exception Trace.TraceError(ex.Message) return Nothing End Try End Using End Function 

用途:

 Dim clonedDict As Dictionary(Of String, String) = Clone(Of Dictionary(Of String, String))(yourOriginalDict)