我有几个不同的类需要克隆:GenericRow、GenericRows、ParticularRow和ParticularRows。有以下类层次结构: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扩展方法,它就不会正确地复制我想要复制的特定实例的深度副本。这是个好主意吗?
发布于 2010-05-26 17:26:19
进入一个会议所以只有时间向你扔一些代码。
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-26 17:28:51
实现ICloneable不是一个好主意(请参阅框架设计指南)。
用BinaryFormatter实现克隆方法是.有意思的。
实际上,我建议为每个类编写单独的克隆方法。
public Class1 Clone()
{
var clone = new Class1();
clone.ImmutableProperty = this.ImmutableProperty;
clone.MutableProperty = this.MutableProperty.Clone();
return clone;
}是的,你重复了很多次,但它仍然是最好的解决方案,IMHO。
https://stackoverflow.com/questions/2915279
复制相似问题