呼,忙活了半天,找到了两种deep copy的方法,feiyun0112说了其中一种,
在微软的文档(http://samples.gotdotnet.com/quickstart/howto/doc/clone.aspx)中
也提到了这种方式,不过相比另外一种方式,我觉得还是不太好,因为如果一旦类的定义发生了变化,那么你将不得不搜索所有deep copy的客户代码来进行修改,如果数量很多的话,那会是一场恶梦。
第二种方法是为你的类实现ISerializable接口,这样修改了类定义之后也只需要修改ISerializable接口实现即可。
ISerializable接口如何实现请参看MSDN。
如何使用请参看下面的代码:(VB.NET代码,我没有时间再去修改了,请自行转换为C#)
<Serializable()> _
Class TheClass
' make sure all the members are serializable :)
....
End Class
dim arr as new arraylist
for i as integer = 1 to 100
arr.add(new theclass)
next
dim mem as new memroystream
dim bf as new binaryformatter
bf.serialize(mem, arr)
mem.seek(seekorigin.begin) ' put the pointer back or you get an error..
dim newarr as arraylist = directcast(bf.deserialize(mem), theclass)
ArrayList myAL = new ArrayList();
Test t = new Test();
t.AA = "111";
myAL.Add(t);
ArrayList myALCopy = new ArrayList();
for (int i = 0; i < arraylist1.Count; i++)
{
Test tcopy = new Test();
tcopy.AA =((Test)myAL[i]).AA;
myALCopy.Add(tcopy);
}