Hashtable和ArrayList等经常需要深度拷贝,而.Net没有现成的函数可以调用,我从国外找了一个方法
public
object
Clone()
{
BinaryFormatter Formatter = new BinaryFormatter( null , new StreamingContext(StreamingContextStates.Clone));
MemoryStream stream = new MemoryStream();
Formatter.Serialize(stream, this );
stream.Position = 0 ;
object clonedObj = Formatter.Deserialize(stream);
stream.Close();
return clonedObj;
}
继承了Clonable接口之后,像这样重写Clone()方法就可以了,他利用了序列化和反序列化的原理,将序列化的流丢入内存,再从内存中反序列化回来就OK了!
{
BinaryFormatter Formatter = new BinaryFormatter( null , new StreamingContext(StreamingContextStates.Clone));
MemoryStream stream = new MemoryStream();
Formatter.Serialize(stream, this );
stream.Position = 0 ;
object clonedObj = Formatter.Deserialize(stream);
stream.Close();
return clonedObj;
}
本文详细介绍了如何在C#中实现深度拷贝,包括使用BinaryFormatter进行序列化和反序列化的方法,并通过实例展示了具体操作过程。
2531

被折叠的 条评论
为什么被折叠?



