首页 日志

C# List 复制

废话不多说,看代码:

方法一:

      List<string> t = new List<string>(); //original

      List<string> t2 = new List<string>(t.ToArray()); // copy of t

 

方法二:

 

 

It is a one liner using LINQ.

      List<string> list1 = new List<string>();
      List<string> list2 = new List<string>();

      // This will copy all the items from list 1 to list 2
      list1.ForEach(i => list2.Add(i));


C#深度拷贝(Deep Copy)

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了!

posted on 2013-08-19 17:01  zly2000a  阅读(824)  评论(0编辑  收藏  举报

导航