我需要对我的复杂对象模型执行深度克隆。在.Net中,你认为最好的方法是什么?
我考虑过序列化/反序列化
不需要提到MemberwiseClone
不够好。
我需要对我的复杂对象模型执行深度克隆。在.Net中,你认为最好的方法是什么?
我考虑过序列化/反序列化
不需要提到MemberwiseClone
不够好。
如果您正在运行部分受信任的环境(例如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));
}
手动实现是最好的方式。这样会比任何其他通用方法都更快。此外,还有很多关于这个操作的库(你可以在这里看到一些带有性能基准的列表)。
顺便说一句,BinaryFormatter对于这个任务非常慢,只适合于测试。
最好的方法可能是在你的对象及其所有需要自定义深度克隆功能的字段中实现System.ICloneable接口。然后,你实现Clone方法以返回你的对象及其成员的深层副本。