2

我有几个不同的类希望被克隆: GenericRowGenericRowsParticularRowParticularRows. 有以下类层次结构: GenericRow是 的父级ParticularRow,并且GenericRows是 的父级ParticularRows。每个类都实现ICloneable,因为我希望能够创建每个实例的深层副本。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();
}

我对每个类中看起来大致相同的便利包装器方法感到满意,因为它的代码非常少,而且它在返回类型、强制类型转换等方面确实因类而异。但是,在所有四个类中ICloneable.Clone()都是相同的。我可以以某种方式抽象它,以便它只在一个地方定义吗?我担心的是,如果我制作了一些实用程序类/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.DeepCopyViaBinarySerialization(this);
}
于 2010-05-26T17:26:19.980 回答
1

实现 ICloneable 不是一个好主意(请参阅框架设计指南)。

使用 BinaryFormatter 实现 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 回答