2

クローン可能にしたいいくつかの異なるクラスがあります: GenericRowGenericRowsParticularRow、およびParticularRows。次のクラス階層があります。 GenericRowは の親でありParticularRowGenericRowsは の親ですParticularRowsICloneable各クラスのインスタンスのディープ コピーを作成できるようにするために、各クラスを実装します。Clone()各クラスでまったく同じコードを書いていることに気づきました。

object ICloneable.Clone()
{
    object clone;

    using (var stream = new MemoryStream())
    {
        var formatter = new BinaryFormatter();

        // Serialize this object
        formatter.Serialize(stream, this);
        stream.Position = 0;

        // Deserialize to another object
        clone = formatter.Deserialize(stream);
    }

    return clone;
}

次に、次のような便利なラッパー メソッドを提供しますGenericRows

public GenericRows Clone()
{
    return (GenericRows)((ICloneable)this).Clone();
}

コードは非常に小さく、戻り値の型、キャストなどによってクラスごとに異なるため、各クラスでほぼ同じように見える便利なラッパーメソッドで問題ありませんただし、 4つのクラスすべてICloneable.Clone()同じです。これを何らかの形で抽象化して、1 か所だけで定義することはできますか? 私の懸念は、ユーティリティ クラス/object拡張メソッドを作成した場合、コピーしたい特定のインスタンスのディープ コピーが正しく作成されないことでした。とにかくこれは良い考えですか?

4

2 に答える 2

2

会議に向かっているので、コードを投げる時間しかありません。

public static class Clone
{
    public static T DeepCopyViaBinarySerialization<T>(T record)
    {
        using (MemoryStream memoryStream = new MemoryStream())
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            binaryFormatter.Serialize(memoryStream, record);
            memoryStream.Position = 0;
            return (T)binaryFormatter.Deserialize(memoryStream);
        }
    }
}

Clone メソッド内から:

Clone()
{
  Clone.DeepCopyViaBinarySerialization(this);
}
于 2010-05-26T17:26:19.980 に答える
1

ICloneable の実装はお勧めできません (フレームワーク設計ガイドラインを参照)。

BinaryFormatter を使用して Clone メソッドを実装するのは....興味深いものです。

実際には、クラスごとに個別の Clone メソッドを作成することをお勧めします。

public Class1 Clone()
{
    var clone = new Class1();
    clone.ImmutableProperty = this.ImmutableProperty;
    clone.MutableProperty = this.MutableProperty.Clone();
    return clone;
}

はい、これで何度も繰り返しますが、それでも私見の最良の解決策です。

于 2010-05-26T17:28:51.710 に答える