c# - 克隆整个对象图

标签 c# serialization datacontract object-graph

在使用这段代码序列化一个对象时:

public object Clone()
{
    var serializer = new DataContractSerializer(GetType());
    using (var ms = new System.IO.MemoryStream())
    {
        serializer.WriteObject(ms, this);
        ms.Position = 0;
        return serializer.ReadObject(ms);
    }
}

我注意到它不会复制关系。 有什么办法可以做到这一点吗?

最佳答案

只需使用接受 preserveObjectReferences 的构造函数重载,并将其设置为 true:

using System;
using System.Runtime.Serialization;

static class Program
{
    public static T Clone<T>(T obj) where T : class
    {
        var serializer = new DataContractSerializer(typeof(T), null, int.MaxValue, false, true, null);
        using (var ms = new System.IO.MemoryStream())
        {
            serializer.WriteObject(ms, obj);
            ms.Position = 0;
            return (T)serializer.ReadObject(ms);
        }
    }
    static void Main()
    {
        Foo foo = new Foo();
        Bar bar = new Bar();
        foo.Bar = bar;
        bar.Foo = foo; // nice cyclic graph

        Foo clone = Clone(foo);
        Console.WriteLine(foo != clone); //true - new object
        Console.WriteLine(clone.Bar.Foo == clone); // true; copied graph

    }
}
[DataContract]
class Foo
{
    [DataMember]
    public Bar Bar { get; set; }
}
[DataContract]
class Bar
{
    [DataMember]
    public Foo Foo { get; set; }
}

关于c# - 克隆整个对象图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2417023/

相关文章:

c# - 如何从枚举中的数据创建对象列表?

python - 使用 flask 棉花糖序列化几何

c# - 为什么序列化的 DataContracts 中有虚假的 URL?

ruby - 无法将 BigDecimal 强制转换为 BigDecimal

.net - 与 XML 序列化的奇遇

c# - WCF:仅返回 json 上的必要属性

c# - 将安全组添加到文件夹问题/System.Security.Principal.IdentityNotMappedException :

c# - 连接关闭后,MySql 临时表仍然存在(来自.NET)

c# - 在 C# 中多线程访问 WPF GUI

python - Django Rest框架非模型序列化器