来源地址:http://www.blogjava.net/TiGERTiAN/archive/2008/02/12/179726.html
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;
}
{
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了!