Project, you will often encounter a copy of the object you want to create as a temporary variable or other use, you need a new object to come out,
It then assigns the various properties of the source object to the new object, so that the properties of the new object are changed in time, and the source object is not changed, that is, the deep copy.
Obviously, it is not only tedious and error-prone to assign a property of an object to another object in a hard-coded way, and the object's class deletes an attribute.
This copy is required to "lose" this property.
Take the employee class for example, the following code implements the deep copy and shallow copy of the employee:
Employee class:
[Serializable] Public classemployee:icloneable { Public stringIdcode {Get;Set; } Public intAge {Get;Set; } //Note that the Department class is labeled with a serialized tag [Serializable],//because the employee is to be serialized, all of its attributes can be serialized PublicDepartment Department {Get;Set; } /// <summary> ///Deep Copy/// </summary> /// <returns></returns> PublicEmployee Deepclone () {using(Stream Objectstream =NewMemoryStream ()) {IFormatter Formatter=NewBinaryFormatter (); Formatter. Serialize (Objectstream, This); Objectstream. Seek (0, Seekorigin.begin); returnFormatter. Deserialize (Objectstream) asEmployee; } } /// <summary> ///Shallow Copy/// </summary> /// <returns></returns> PublicEmployee Shallowclone () {returnClone () asEmployee; } /// <summary> ///Create a shallow copy of the current System.Object/// </summary> /// <returns></returns> Public ObjectClone () {return This. MemberwiseClone (); } }
View Code
Department class:
[Serializable] Public class Department { publicstringgetset;} Public Override string ToString () { returnthis. Name; } }
View Code
Main method:
Static voidMain (string[] args) {Employee EMP1=NewEmployee {Idcode="10086", Age= at, Department=NewDepartment {Name ="Information Technology Department" } }; //Shallow Copy//Employee emp2 = emp1. Shallowclone () as Employee; //Deep CopyEmployee EMP2=EMP1. Deepclone () asEmployee; //Modifying the individual properties of EMP2,EMP1 is not modifiedEmp2. Idcode ="10087"; Emp2. Age= -; Emp2. Department.name="Research Department"; //Output ValidationConsole.WriteLine ("number: {0}, department: {1}, Age: {2}", Emp1. Idcode,emp1. Department,emp1. Age); Console.WriteLine ("number: {0}, department: {1}, Age: {2}", EMP2. Idcode, EMP2. Department, EMP2. Age); Console.readkey (); }
View Code
Run:
Summary: EMP2 is a copy of the EMP1 deep copy, modifying the properties of the EMP2, the EMP1 properties will not change.
Deep copy and shallow copy