Using System; using System. collections. generic; using System. linq; using System. text; using System. IO; using System. runtime. serialization. formatters. binary; namespace CloneClass {class Program {static void Main (string [] args) {Results set1 = new Results (); Result result1 = new Result (); result1.ResultId = "1 "; result1.ResultName = "kp"; set1.ResultSetId = "Set1"; set1.result = result1; // The operator value is Results set2 = set1; // Results set3 = (Results) set1.Clone (); // deep clone Results set4 = (Results) set1.DeepClone (); set1.ResultSetId = "Set2"; set1.result. resultName = "Shikyoh"; Console. writeLine ("operator value assignment result"); Console. writeLine (set2.ResultSetId + "," + set2.result. resultId + "," + set2.result. resultName); Console. writeLine ("shortest clone result"); Console. writeLine (set3.ResultSetId + "," + set3.result. resultId + "," + set3.result. resultName); Console. writeLine ("Deep clone result"); Console. writeLine (set4.ResultSetId + "," + set4.result. resultId + "," + set4.result. resultName); Console. readLine () ;}} [Serializable] public class Result {public string ResultId; public string ResultName;} [Serializable] public class Results {public string ResultSetId; public Result result; public object Clone () {return this. memberwiseClone ();} public object DeepClone () {MemoryStream steam = new MemoryStream (); BinaryFormatter formatter = new BinaryFormatter (); formatter. serialize (steam, this); steam. position = 0; return formatter. deserialize (steam );}}}
Result:
A copy of a simple reference type. Or point to the same address.
Shortest cloning can only clone members in this class
All clones are cloned in depth to fully implement the cloning effect.
Refer:
MemberwiseCloneMethod To create a superficial copy, specifically to create a new object, and then copy the non-static fields of the current object to the new object. If the field is of the value type, perform a step-by-step copy on the field. If the field is of reference type, the referenced object is copied but not referenced. Therefore, the original object and its counterparts reference the same object.
To achieve deep replication, We must traverse graphs composed of mutually referenced objects and process the cyclic reference structure. This is undoubtedly very complicated. Fortunately, with the serialization and deserialization mechanisms of. Net, an object can be cloned in depth. The principle is very simple. First, serialize the object to the memory stream. At this time, the state of the object referenced by the object is saved to the memory .. Net serialization mechanism will automatically handle the situation of loop reference. Then, status information in the memory stream is deserialized into a new object. This completes the deep replication of an object. In the prototype design mode, CLONE is critical.