質問

オブジェクトをシリアル化するためにこのコードを使用している間

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

他のヒント

のどちらか[DataContract]であなたのクラスに注釈を付けるかDatacontractSerializerのコンストラクタであなたの子供のタイプを追加します。

var knownTypes = new List<Type> {typeof(Class1), typeof(Class2), ..etc..};
var serializer = new DataContractSerializer(GetType(), knownTypes);

あなたはバイナリシリアライザを使用して検討するかもしれない深いクローンを実行するには:

public static object CloneObject(object obj)
{
    using (var memStream = new MemoryStream())
    {
        var binaryFormatter = new BinaryFormatter(
             null, 
             new StreamingContext(StreamingContextStates.Clone));
        binaryFormatter.Serialize(memStream, obj);
        memStream.Seek(0, SeekOrigin.Begin);
        return binaryFormatter.Deserialize(memStream);
    }
}

あなたはシリアライズ/デシリアライズステップの間、オブジェクトのアイデンティティを維持するために、バイナリシリアライザを必要とします。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top