Introduction to C # about the Clone () method

Source: Internet
Author: User

Daily PA PA code, often encountered shallow copy and deep copy of the problem, the following on their own experience write, there are questions please leave a message!

For example, I have a simple class:

class people{    publicint  _age;    publicstring  _name;      Public People (int age,string  name)    == Name;}    }

Common assignment statements, such as:

New People ("Mike"= Mike;

This is a shallow copy that shares the same block of memory, like a pointer, that Mike2 and Mike objects simultaneously point to the memory that Mike requested when he was new.
Now I add a clone () method to the People class:

classpeople{ Public int_age;  Public string_name;  PublicPeople (intAge,stringName) {_age=Age ; _name=Name; }     Public ObjectClone () {People myself=NewPeople ( This. _age, This. _name); returnmyself;    }}

It is clear that the object returned by the call to the Clone () method is an entirely new object, which is a newly instantiated object but is equal to the original object on the value.

New People ("Mike"== Mike.clone () as people;

Mike2 and Mike3 are equal in value, but are actually completely independent objects.

" Jone " ; // after executing the above code, Mike's _name property changes, and Mike3 does not change. 

Introduction to C # about the Clone () method

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.