2003年12月1日 22:01 - (阅读:5391;评论:9)
下面的工具函数可以构造source对象的deep copy,很有用!不妨一试
using System.IO;
using System.Runtime.Serialization.Binary;
public object static DeepClone(object source)
{
? if (source==null) return null;
? using (MemoryStream stream = new MemoryStream())
? {
??? BinaryFormatter?formatter = new BinaryFormatter();
??? formatter.Serialize(stream, source);
??? stream.Position = 0;
??? return?formatter.Deserialize(stream);
? }
}
反馈
# 回复: C# .NET Tips: Deep Cloning an Object
2003-12-1 22:07 by
原来这样都可以,学到了:)
# 回复: C# .NET Tips: Deep Cloning an Object
2003-12-2 8:26 by
object默认的clone是shallow copy :(
# 回复: C# .NET Tips: Deep Cloning an Object
2003-12-2 9:44 by
@sam111:
Nice translation and expansion. In this tip I just shown an easy way to implement object cloning by means of "binary serialization". And because binary serialization is kind of deep serialization, the result is a deep cloned object graph. Thanks for your article for us all.
@kkwoof:
System.Object has a "protected" (but non-virtual) method called MemberwiseClone which is implemented to make a "shallow clone" of any object instance. Since the method is "protected", you need a way to "public"-ize the functionality by some means, say, IClonable or any public method. But if you wanna expose the fully recursively (I mean, deep) cloning functionality to the outside, this tip will be your first aid. :)
# 回复: C# .NET Tips: Deep Cloning an Object
2003-12-2 10:21 by
sam111,请教一个问题:
BinaryFormatter和SoapFormatter以及.NET Remoting都使用Deep Serialization技术,。。。。。。。。。
你这里所说的deep,是不是说对哪些没有手工实现Iclonable的类?
如果自己实现了getobjectdata(),那么BinaryFormatter 还会
做深度的序列化吗?
# 回复: C# .NET Tips: Deep Cloning an Object
2003-12-2 13:51 by
To JGTM:
上周你似乎询问过我,你应该写什么体裁的随笔,不过那时候没有什么概念,现在看了你在我的随笔以及别人随笔后的评论,我想我已经有思路了。
你可以虚拟一个团队,共同开发一个项目,这个项目最好通用一些,比如论坛的开发,然后就架构设计、实体类粒度等等来写一系列的随笔。以“讲故事”的方式给大家阐述一下你心目中完美的.NET的开发,从团队、技术、人员上等等来描述,不牵涉到人为因素。
在最后,你还可以再阐述一下在项目进度的压力下,如何简化开发模型,使开发即可以可控,又可以适应更快速开发的要求:D
不知道意下如何?
MSN上不去,没有办法跟你说了:D
# 回复: C# .NET Tips: Deep Cloning an Object
2003-12-2 16:35 by
hehe, your answer is very great:)
# re: C# .NET Tips: Deep Cloning an Object
2004-12-10 9:15 by
public object static DeepClone(object source)
说source不支持Serialization,是怎么回事?
<script type="text/javascript" src="http://www.google-analytics.com/urchin.js"> </script> <script type="text/javascript"> _uacct = "UA-247852-1"; urchinTracker(); </script>