克隆参考类型 [英] Cloning a reference type

查看:43
本文介绍了克隆参考类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下内容

我有一个HTML模板对象

I have an Html Template object

   class HtmlTemplateModel
    {
       public HTML Html {get;set;}
       //..etc
    }

和一个HTML编辑器

class HtmlEditorViewModel
{
   private HtmlTemplateModel htmlTemplateModel;
   public HtmlEditor(HtmlTemplateModel htmlTemplateModel)
   {
      this.htmlTemplateModel = htmlTemplateModel;
   }
}

通过这种方式,TemplateEditor实例将更改应用于原始模板,因为它是引用类型,但是我不想修改其值,所以我制作了一个新的构造函数,该构造函数采用 HtmlTemplateModel 并创建一个新的 HtmlTemplateModel .

This way the TemplateEditor instance applies the changes to the original template since its a reference type, but i dont want to modify its value so i made a new constructor that takes an HtmlTemplateModel and creates a new HtmlTemplateModel.

  • 这是在.NET中克隆引用类型的最佳方法吗?
  • 是否有快捷方式,这样我就不必创建另一个构造函数来克隆对象?

推荐答案

一种简单的方法是序列化对象,它将对源对象进行深层复制.

A simple way is to serialize the object, it will make a deep copy of the source object.

http://www.codeproject.com/Articles/23832/通过序列化对象实现深层克隆

这篇关于克隆参考类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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