代码之家  ›  专栏  ›  技术社区  ›  Sarah Vessels

ICloneable在几个类中的实现

  •  2
  • Sarah Vessels  · 技术社区  · 14 年前

    我有几个不同的类,我想克隆: GenericRow GenericRows , ParticularRow ,和 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;
    }
    

    然后我提供了一个方便的包装器方法,例如 :

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

    不同的类在返回类型、类型转换等方面有所不同, ICloneable.Clone() 完全相同的 在所有四个班级。我能把它抽象成一个地方吗?我担心的是如果我上了实用课/ object 扩展方法时,它不会正确地对我要复制的特定实例进行深度复制。这是个好主意吗?

    2 回复  |  直到 14 年前
        1
  •  2
  •   Sarah Vessels    14 年前

    参加一个会议,所以只有时间向你扔一些代码。

    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
  •  1
  •   dtb    14 年前

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

    使用BinaryFormatter实现克隆方法是。。。。很有趣。

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

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