Cloning is a new object created as a copy of the current instance.
Cloning can be divided into deep cloning and shortest cloning.
Deep clone: All members of the current instance are cloned.
Simple clone: Only all values of the current instance are cloned.
The simple clone Object class provides us with a protected clone method MemberwiseClone ()
Deep cloning should be implemented by ourselves
There are generally two methods for implementing deep cloning... (I only know two... If you know other methods, please reply to me ..)
I will create two classes
The Address class has two attributes: Province and City.
Code
[Serializable] // indicates that this class can be serialized.
Public class Address
{
Private string _ city;
Public string City
{
Get {return _ city ;}
Set {_ city = value ;}
}
Private string _ province;
Public string Province
{
Get {return _ province ;}
Set {_ province = value ;}
}
}
The Person class has three attributes: Name, Age, and Address.
Code
[Serializable]
Public class Person
{
Private string _ name;
Private int _ age;
Private Address _ address;
Public Person (string name, int age, Address address)
{
_ Name = name;
_ Age = age;
_ Address = address;
}
Public Person ()
{
}
Public Address
{
Get {return _ address ;}
Set {_ address = value ;}
}
Public string Name
{
Get {return this. _ name ;}
Set {this. _ name = value ;}
}
Public int Age
{
Get {return _ age ;}
Set {_ age = value ;}
}
}
Now let's clone the Person.
Add to Person class
Code
Public Person Clone ()
{
MemoryStream MS = new MemoryStream ();
BinaryFormatter bf = new BinaryFormatter ();
Ms. Seek (0, SeekOrigin. Begin );
Bf. Serialize (MS, this );
Ms. Seek (0, SeekOrigin. Begin );
Return (Person) bf. Deserialize (MS );
}
This method can be cloned.
This method is convenient to clone by using serialization and deserialization, but the class must be marked as Serializable.
Order a method
Code
Public Person Clone ()
{
Person temp = new Person ();
Temp. Name = this. Name;
Temp. Age = this. Age;
Temp. Address. Province = this. Address. Province;
Temp. Address. City = this. Address. City;
Return temp;
}
This method is prone to errors when there are too many members of a class. This cloning method also needs to be modified when you want to modify the class members.
We recommend that you use the serialization method.
Simple cloning is easy. Call the protected cloning method MemberwiseClone ().
Code
Public Person Clone ()
{
Return this. MemberwiseClone ();
}