Deep copy and shallow copy

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.