我想要克隆几个不同的类:GenericRow
、GenericRows
、PspecialRow
和 PspecialRows
>。存在以下类层次结构:GenericRow
是PspecialRow
的父级,GenericRows
是PspecialRows
的父级。每个类都实现 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/