加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 克隆整个对象图

发布时间:2020-12-15 18:17:15 所属栏目:百科 来源:网络整理
导读:使用此代码序列化对象时: 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); }}
使用此代码序列化对象时:
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; }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读