Duplicate Object and working with Duplicate without changing Original

后端 未结 8 591
逝去的感伤
逝去的感伤 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:41

    As of c# 4.5 the base class object contains a method called MemberwiseClone that enables you to perform a shallow copy of that object and returns the result as a new instance. (If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object.)

    This is useful if you are looking to implement a prototype design pattern.

    If you are looking to implement a deep copy (everything within the class is duplicated as new instances) then serialization or reflection are probably the best tools

    0 讨论(0)
  • 2020-12-08 14:44

    To duplicate an object by value instead of reference, you can serialize it (e.g. JSON) and then deserialize it right after. You then have a copy by value.

    Here's an example

    ItemVO originalItemVO = new ItemVO();
    originalItemVO.ItemId = 1;
    originalItemVO.ItemCategory = "ORIGINAL";
    
    string json = Newtonsoft.Json.JsonConvert.SerializeObject(originalItemVO); 
    ItemVO duplicateItemVO = Newtonsoft.Json.JsonConvert.DeserializeObject<ItemVO>(json);
    
    0 讨论(0)
提交回复
热议问题