Duplicate Object and working with Duplicate without changing Original

后端 未结 8 588
逝去的感伤
逝去的感伤 2020-12-08 14:02

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

ItemVO originalItemVO = new ItemVO();
originalItemVO.ItemId = 1;         


        
8条回答
  •  有刺的猬
    2020-12-08 14:35

    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.

提交回复
热议问题