复制对象并使用复制对象而不更改原始对象 [英] Duplicate Object and working with Duplicate without changing Original

查看:48
本文介绍了复制对象并使用复制对象而不更改原始对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个对象ItemVO,其中已经分配了一堆属性。
例如:

Assuming I have an Object ItemVO in which there a bunch of properties already assigned. eg:

ItemVO originalItemVO = new ItemVO();
originalItemVO.ItemId = 1;
originalItemVO.ItemCategory = "ORIGINAL";

我想使用以下方式创建另一个副本:

I would like to create another duplicate by using :

duplicateItemVO = originalItemVO;

,然后使用plicateItemVO并更改其属性,而无需更改originalItemVO:

and then use the duplicateItemVO and alter its' properties, WITHOUT changing the originalItemVO:

// This also change the originalItemVO.ItemCategory which I do not want.
duplicateItemVO.ItemCategory = "DUPLICATE" 

如何在不更改类的情况下实现这一目标ItemVO?

How can I achieve this, without changing the class ItemVO ?

谢谢

public class ItemVO     
{
    public ItemVO()
    {
        ItemId = "";
        ItemCategory = "";
    }

    public string ItemId { get; set; }
    public string ItemCategory { get; set; }
}


推荐答案

您需要构造一个新的类实例,而不仅仅是分配变量:

You would need to construct a new instance of your class, not just assign the variable:

duplicateItemVO = new ItemVO 
    { 
        ItemId = originalItemVO.ItemId, 
        ItemCategory = originalItemVO.ItemCategory 
    };

在处理引用类型(任何类)时,仅分配变量即创建副本对原始对象的引用。因此,在该对象内设置属性值也会更改原始对象。为了防止这种情况,您实际上需要构造一个新的对象实例。

When you're dealing with reference types (any class), just assigning a variable is creating a copy of the reference to the original object. As such, setting property values within that object will change the original as well. In order to prevent this, you need to actually construct a new object instance.

这篇关于复制对象并使用复制对象而不更改原始对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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