你如何做一个深层副本对象在.net(C#专)? [英] How do you do a deep copy an object in .Net (C# specifically)?

查看:356
本文介绍了你如何做一个深层副本对象在.net(C#专)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有一个真正的深层副本。在Java中,这很简单,但你怎么做它在C#?

I want a true deep copy. In Java, this was easy, but how do you do it in C#?

推荐答案

我已经看到了一些不同的方法,但我用一个通用的实用方法,例如:

I've seen a few different approaches to this, but I use a generic utility method as such:

public static T DeepClone<T>(T obj)
{
 using (var ms = new MemoryStream())
 {
   var formatter = new BinaryFormatter();
   formatter.Serialize(ms, obj);
   ms.Position = 0;

   return (T) formatter.Deserialize(ms);
 }
}

注:

    为了使这项工作
  • 您的类必须被标记为 [Serializable接口]
  • 您的源文件都必须包括以下code:

  • Your class MUST be marked as [Serializable] in order for this to work.
  • Your source file must include the following code:

using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

这篇关于你如何做一个深层副本对象在.net(C#专)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆