我需要在我的复杂对象模型上执行深度克隆.您认为在.Net中做到这一点的最佳方式是什么?
我想到序列化/反序列化
没有必要提到MemberwiseClone不够好.
Mar*_*ell 15
如果您控制对象模型,那么您可以编写代码来执行此操作,但这需要大量维护.但是,存在许多问题,这意味着除非您需要绝对最快的性能,否则序列化通常是最易于管理的答案.
这是BinaryFormatter可以接受的案例之一; 通常我不是粉丝(由于版本控制等问题) - 但由于序列化数据是立即消费,这不是问题.
如果你想要它快一点(但没有你自己的代码),那么protobuf-net可能有所帮助,但需要更改代码(添加必要的元数据等).它是基于树的(不是基于图形的).
其他序列化程序(XmlSerializer,DataContractSerializer)也很好,但如果它只是用于克隆,它们可能不会提供太多BinaryFormatter(除非可能XmlSerializer不需要)[Serializable].
所以真的,这取决于你的确切类和场景.
小智 9
如果您在部分信任环境(例如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);
}
}
Run Code Online (Sandbox Code Playgroud)
来自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));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11278 次 |
| 最近记录: |