【问题标题】:DRYing out implementation of ICloneable in several classes在几个类中干燥 ICloneable 的实现
【发布时间】:2011-02-24 07:25:31
【问题描述】:

我想克隆几个不同的类:GenericRowGenericRowsParticularRowParticularRows。有以下类层次结构:GenericRowParticularRow 的父级,GenericRowsParticularRows 的父级。每个类都实现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();
}

我很满意每个类中的便利包装方法看起来都差不多,因为它的代码非常少,而且它确实在返回类型、类型转换等方面因类而异。但是,@987654334 @ 在所有四个类中相同。我可以以某种方式抽象它,以便它只在一个地方定义吗?我担心的是,如果我创建了一些实用程序类/object 扩展方法,它不会正确地制作我想要复制的特定实例的深层副本。这是个好主意吗?

【问题讨论】:

    标签: c# clone dry abstraction deep-copy


    【解决方案1】:

    要去开会,所以只有时间向你扔一些代码。

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

    【讨论】:

    【解决方案2】:

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

    使用 BinaryFormatter 实现 Clone 方法很有趣。

    我实际上建议为每个类编写单独的克隆方法,例如

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

    是的,您重复了很多次,但恕我直言,它仍然是最好的解决方案。

    【讨论】:

    • 大声笑@'有趣'。给我的代码就是这样深拷贝的,我从不费心去修改它。
    猜你喜欢
    • 1970-01-01
    • 2012-01-04
    • 1970-01-01
    • 2017-02-11
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多