`
ay_guobo
  • 浏览: 114355 次
  • 性别: Icon_minigender_1
  • 来自: 札幌
社区版块
存档分类
最新评论

C#深度拷贝(Deep Copy)

    博客分类:
  • C#
阅读更多

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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics