Duplicate Object and working with Duplicate without changing Original

后端 未结 8 589
逝去的感伤
逝去的感伤 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: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(json);
    

提交回复
热议问题