.Net深度克隆 - 最好的方法是什么?

Adi*_*rda 11 .net c# clone

我需要在我的复杂对象模型上执行深度克隆.您认为在.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)


Qry*_*taL 5

来自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)


Pat*_*and 0

最好的方法可能是在您的对象及其所有还需要自定义深度克隆功能的字段中实现 System.IClonable 接口。然后,您实现Clone方法以返回对象及其成员的深层副本。

  • 仍然有一些建议反对这一点,我同意它们。IClonable 在一个对象上可能意味着深,而在另一个对象上则意味着浅。打电话的时候没有办法辨别。当然,这确实并不完全适用于内部项目,但尽早认识到并不是一个坏习惯。 (2认同)