gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:45:45 25 4
gpt4 key购买 nike

我有几个不同的类需要克隆: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();
}

我对便利的包装方法在每个类中看起来都一样很好,因为它的代码很少,而且它确实在返回类型、转换等方面因类而异。但是,ICloneable.Clone() 在所有四个类中相同。我能以某种方式抽象它以便它只在一个地方定义吗?我担心的是,如果我制作了一些实用程序类/object 扩展方法,它不会正确制作我想要复制的特定实例的深拷贝。这是个好主意吗?

最佳答案

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

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()
{
Clone.DeepCopyViaBinarySerialization(this);
}

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com