c# - 在几个类中干燥 ICloneable 的实现

标签 c# clone dry abstraction deep-copy

我想要克隆几个不同的类:GenericRowGenericRowsPspecialRowPspecialRows >。存在以下类层次结构:GenericRowPspecialRow 的父级,GenericRowsPspecialRows 的父级。每个类都实现 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 扩展方法,它将无法正确地对我想要复制的特定实例进行深层复制。无论如何,这是一个好主意吗?

最佳答案

即将参加 session ,因此只有时间向您抛出一些代码。

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

关于c# - 在几个类中干燥 ICloneable 的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2915279/

相关文章:

c# - 修复了 XAML 中的定位

c# - 如何将选定的TreeView项目传递给RelayCommand,而无需后面的代码

ruby-on-rails-3 - cucumber + 重复步骤 + Rails 3

python - Google Cloud Endpoints API 的 DRY 代码

php - 在类中的多个函数中重复使用的代码块 - 如何应用 DRY

c# - 使用 C# 检查字符串是否包含字符串数组中的字符串

c# - 如何保护我的程序集不被其他人使用?

java - LinkedList深拷贝java

javascript - jQuery .wrap() 没有环绕克隆的元素

git - 克隆裸 git 存储库的单个路径