JGTM'2008 [MVP]

Thinking in WPF...
随笔 - 36, 评论 - 453, 引用 - 16

导航

标签

每月存档

最新留言

广告

 

下面的工具函数可以构造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);

? }

}

打印 | 张贴于 2003-12-01 22:01:00 | Tag:.NET Stuffs

留言反馈

#回复: C# .NET Tips: Deep Cloning an Object 编辑
在class定义前面什么需要Serize即可,加上【Serialbe()】就可以了。
2007-08-16 03:50:00 | [匿名:C# dev]
#re: C# .NET Tips: Deep Cloning an Object 编辑
public object static DeepClone(object source)
说source不支持Serialization,是怎么回事?
2004-12-10 09:15:00 | [匿名:wdf]
#回复: C# .NET Tips: Deep Cloning an Object 编辑
hehe, your answer is very great:)
2003-12-02 16:35:00 | [匿名:sam1111]
#回复: C# .NET Tips: Deep Cloning an Object 编辑
To JGTM:
上周你似乎询问过我,你应该写什么体裁的随笔,不过那时候没有什么概念,现在看了你在我的随笔以及别人随笔后的评论,我想我已经有思路了。
你可以虚拟一个团队,共同开发一个项目,这个项目最好通用一些,比如论坛的开发,然后就架构设计、实体类粒度等等来写一系列的随笔。以“讲故事”的方式给大家阐述一下你心目中完美的.NET的开发,从团队、技术、人员上等等来描述,不牵涉到人为因素。
在最后,你还可以再阐述一下在项目进度的压力下,如何简化开发模型,使开发即可以可控,又可以适应更快速开发的要求:D
不知道意下如何?
MSN上不去,没有办法跟你说了:D
2003-12-02 13:51:00 | [匿名:开心就好]
#回复: C# .NET Tips: Deep Cloning an Object 编辑
sam111,请教一个问题:
BinaryFormatter和SoapFormatter以及.NET Remoting都使用Deep Serialization技术,。。。。。。。。。

你这里所说的deep,是不是说对哪些没有手工实现Iclonable的类?
如果自己实现了getobjectdata(),那么BinaryFormatter 还会
做深度的序列化吗?
2003-12-02 10:21:00 | [匿名:kkwoof]
#回复: C# .NET Tips: Deep Cloning an Object 编辑
@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. :)
2003-12-02 09:44:00 | [匿名:JGTM'2003]
#回复: C# .NET Tips: Deep Cloning an Object 编辑

object默认的clone是shallow copy :(
2003-12-02 08:26:00 | [匿名:kkwoof]
#回复: C# .NET Tips: Deep Cloning an Object 编辑
原来这样都可以,学到了:)
2003-12-01 22:07:00 | [匿名:mic]
对不起,目前本随笔不允许发表新评论.

Powered by: Joycode.MVC引擎 0.5.2.0