Reading Comprehension-C # shallow copy and deep copy

Source: Internet
Author: User

Reading Comprehension-C # shallow copy and deep copy:
The memberwiseclone method creates a superficial copy by creating a new object and then copying 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.
Deep copy, that is, the icloneable interface. icloneable can be used for deep copy and light copy.
Please refer to the following sentence.

Using System;
Using System. Collections. Generic;

Public   Class Myclass
{
Class Instancea: icloneable
  {
Public   Int X;
Public Instanceb B;
Public Instancea () {}
Public Instancea ( Int X, instanceb B)
{
This. X=X;
This. B=B;
}
Object Icloneable. Clone ()
{
Return This. Clone ();
}
Public Instancea clone ()
{
Instancea = This . Memberwiseclone () As Instancea;
A. B = This . B. Copy ();
Return A; // Deep Replication
// Return (instancea) This. memberwiseclone (); // Light Replication
// Return new instancea (this. X, this. B ); // Use this can't get deep copy too ..

}
}
  Class Instanceb
  {
Public   Int Y;
Public Instanceb copy ()
{
Return This. Memberwiseclone ()AsInstanceb;
}
}
 
  Public   Static   Void Main ()
  {
Instancea obj1 = New Instancea ();
Obj1.x = 1 ;
Obj1. B = New Instanceb ();
Obj1. B. Y = 2 ;

Instancea obj2 = Obj1.clone ();
Obj2.x = 3 ;
Obj2. B. Y = 4 ;
Console. writeline ( " Obj1.x is: {0} \ t obj1. B. Y = {1} " , Obj1.x, obj1. B. y );
Console. writeline ( " Obj2.x is: {0} \ t obj2. B. Y = {1} " , Obj2.x, obj2. B. y );
Console. Readline ();
}
}

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.