I've got a generic dictionary Dictionary that I would like to essentially make a Clone() of ..any suggestions.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
Binary Serialization method works fine but in my tests it showed to be 10x slower than a non-serialization implementation of clone. Tested it on
Dictionary<string , List<double>>
This works fine for me
For .NET 2.0 you could implement a class which inherits from
Dictionary
and implementsICloneable
.You can then clone the dictionary simply by calling the
Clone
method. Of course this implementation requires that the value type of the dictionary implementsICloneable
, but otherwise a generic implementation isn't practical at all.(Note: although the cloning version is potentially useful, for a simple shallow copy the constructor I mention in the other post is a better option.)
How deep do you want the copy to be, and what version of .NET are you using? I suspect that a LINQ call to ToDictionary, specifying both the key and element selector, will be the easiest way to go if you're using .NET 3.5.
For instance, if you don't mind the value being a shallow clone:
If you've already constrained T to implement ICloneable:
(Those are untested, but should work.)
The best way for me is this:
Try this if key/values are ICloneable: