
[英]What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?
[英].Net Deep cloning - what is the best way to do that?
我需要在我的复杂对象模型上执行深度克隆。 您认为在.Net中做到这一点的最佳方式是什么?
我想过序列化/反序列化
无需提及MemberwiseClone
不够好。
如果您控制对象模型,那么您可以编写代码来执行此操作,但这需要大量维护。 但是,存在许多问题,这意味着除非您需要绝对最快的性能,否则序列化通常是最易于管理的答案。
这是BinaryFormatter
可以接受的工作之一; 通常我不是粉丝(由于版本控制等问题) - 但由于序列化数据是立即消费,这不是问题。
如果你想要它快一点(但没有你自己的代码),那么protobuf-net
可能有所帮助,但需要更改代码(添加必要的元数据等)。 它是基于树的(不是基于图形的)。
其他序列化程序( XmlSerializer
, DataContractSerializer
)也很好,但如果它只是用于克隆,它们可能不会提供超过BinaryFormatter
(除了XmlSerializer
可能不需要[Serializable]
。
所以真的,这取决于你的确切类和场景。
如果您在部分信任环境(例如Rackspace Cloud)中运行代码,则可能会限制使用BinaryFormatter。 可以使用XmlSerializer。
public static T DeepClone<T>(T obj)
{
using (var ms = new MemoryStream())
{
XmlSerializer xs = new XmlSerializer(typeof(T));
xs.Serialize(ms, obj);
ms.Position = 0;
return (T)xs.Deserialize(ms);
}
}
来自msdn杂志的深度克隆示例:
Object DeepClone(Object original)
{
// Construct a temporary memory stream
MemoryStream stream = new MemoryStream();
// Construct a serialization formatter that does all the hard work
BinaryFormatter formatter = new BinaryFormatter();
// This line is explained in the "Streaming Contexts" section
formatter.Context = new StreamingContext(StreamingContextStates.Clone);
// Serialize the object graph into the memory stream
formatter.Serialize(stream, original);
// Seek back to the start of the memory stream before deserializing
stream.Position = 0;
// Deserialize the graph into a new set of objects
// and return the root of the graph (deep copy) to the caller
return (formatter.Deserialize(stream));
}
请看一下非常好的文章C#Object Clone Wars 。 我在那里找到了一个非常有趣的解决方案: 可复制:用于复制或克隆.NET对象的框架
最好的方法可能是在对象及其所有需要自定义深度克隆功能的字段中实现System.IClonable接口。 然后,您实现Clone方法以返回对象及其成员的深层副本。
你可以尝试AltSerialize ,它在很多情况下比.Net序列化器更快。 它还提供缓存和自定义属性以加速序列化。
手动实现此方法的最佳方式。 它将比任何其他通用方法更快。 此外,还有很多用于此操作的库(您可以在此处查看一些带有性能基准的列表)。
顺便说一下,BinaryFormatter对于这个任务来说非常慢,并且只能用于测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.