1. Implement the deep COPY method
Using system. io; using system. runtime. serialization; namespace deepcopyexp {class deepcopy {public static t deepcopybydcs <t> (t obj) {T newobject; using (memorystream = new memorystream ()) {datacontractserializer DCS = new datacontractserializer (obj. getType (); DCS. writeobject (memorystream, OBJ); memorystream. seek (0, seekorigin. begin); newobject = (t) DCS. readobject (memorystream) ;}return newobject ;}}}
2. Test the deep COPY method.
2.1 write test code
Using system; namespace deepcopyexp {class program {static void main (string [] ARGs) {student s = new student () {id = 1, name = "March May ", score = new score () {chinesescore = 100, mathscore = 100 }}; student S1 = deepcopy. deepcopybydcs (s); console. writeline ("ID = {0}, name = {1}, score. chinesescore = {2}, score. mathscore = {3} ", s1.id, s1.name, s1.score. chinesescore, s1.score. mathscore) ;}} public class score {public int chinesescore {Get; set;} public int mathscore {Get; Set ;}} public class student {public int ID {Get; set ;}public string name {Get; Set ;}public score {Get; Set ;}}}
The code first instantiates the student class to get the object s, and then uses the copy method provided in this article to copy it to the object S1 and output the content of S1. Is the content of S1 exactly the same as that of S?
2.2 run the test code and obtain the result.
Figure 1 program execution result
From the results, we can see that S and S1 are completely consistent.
3. Is it a deep copy?
To verify this, add the following code after code student S1 = deepcopy. deepcopybydcs (s:
S. ID = 2; S. Name = "sanwuyueer"; S. Score = new score () {chinesescore = 0, mathscore = 0 };
Use these codes to modify the value of object S and output the value of object S1 again. It is found that the content of object S1 has not changed, indicating that S1 is a new object unrelated to object S, it is indeed a deep copy.
4 principle of implementing deep copy in datacontractserializer class
First, use the instance method of the datacontractserializer class writeobject to write the complete content of the object to the stream, then use the instance method readobject to read the stream content and generate the deserialization object.
Use the datacontractserializer class for deep copy operations