gpt4 book ai didi

c# - 克隆整个对象图

转载 作者:太空狗 更新时间:2023-10-29 20:52:18 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com