本文介绍了克隆整个对象图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用此代码序列化一个对象:

While using this code to serialize an object:

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);
    }
}



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

I have noticed that it doesn't copy the relationships.Is there any way to make this happen?

推荐答案

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

Simply use the constructor overload that accepts preserveObjectReferences, and set it to 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; }
}

这篇关于克隆整个对象图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 15:35