您的位置:首页 > 编程语言 > C#

C# ArrayList深度拷贝

2011-01-10 09:02 218 查看
C#中的赋值分为值赋值和引用赋值,在ArrayList中经常需要用到深度拷贝,教程中一般都用介绍使用IClone接口。

本文介绍另外一种思路:

可以将需要赋值的ArrayList先序列化,然后再反序列化,甚至先保存到一个文件中在读回的方式,后一种方式消耗的时间肯定要多于前一种方式。不过先序列化,然后再反序列化与使用IClone接口之间到底有多大的性能差异还没仔细研究,不过对于一般的小程序而言,用序列化-反序列化来实现深度拷贝更加简明。

列子:

......

public void Clone(List<flight> inputList)

{

BinaryFormatter Formatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));

System.IO.MemoryStream stream = new System.IO.MemoryStream();

Formatter.Serialize(stream, inputList);

stream.Position = 0;

flightList = Formatter.Deserialize(stream) as List<flight>;

stream.Close();

}

......
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: