Deep copy implementation

Source: Internet
Author: User
// Implementation of deep copy
// 2004.9.2
Using system;
Using system. collections;
Class reftype {
Public string name;
Public int32 age;
Public reftype (string name, int32 age)
{
This. Name = Name;
This. Age = age;
}
}
// Type mytype implements the icloneable interface, which can be deeply copied
Class mytype: icloneable {
Public reftype R; // reference type field
Public string name; // Value Type field
Public int32 age; // Value Type field
Private arraylist Al = new arraylist ();
Public mytype (string name, int32 age ){
This. Name = Name;
This. Age = age;
R = new reftype (name, age );
This. Al. Add (this. Name );
This. Al. Add (this. Age );
This. Al. Add (this. R );
}
Public object clone ()
{
Mytype c = new mytype (this. Name, this. Age );
C. Al = new arraylist ();
C. Al. Add (this. Name );
C. Al. Add (this. Age );
C. Al. Add (this. R );
Return C;
}
Public mytype deepclone (){
Return (mytype) This. Clone ();
}
}
// Startup class
Class app {
Static void main (){
Mytype M1 = new mytype ("Zhang San", 18); // source object M1
Mytype m2 = (mytype) m1.deepclone (); // the target object m2 is cloned by M1 (deep copy ).
Console. writeline (m2.name. tostring () + "," + m2.age. tostring ());
Console. writeline (m2.r. Name. tostring () + "," + m2.r. Age. tostring ());
M1.name = "Li Si ";
M1.age = 19;
M1.r. Name = "Li Si ";
M1.r. Age = 19;
Console. writeline (m2.name. tostring () + "," + m2.age. tostring (); // The value of the Value Type field is not changed.
Console. writeline (m2.r. Name. tostring () + "," + m2.r. Age. tostring (); // The value of the reference type field has not changed.
}
}

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.