Shallow copy by using Memberwiseclone() method
class Test:ICloneable
{
int a;
Test()
{
a = 20;
}
public int Data
{
se开发者_如何学运维t
{
a= value;
}
}
object Clone()
{
this.MemeberWiseClone();
}
}
Test a = new Test();
Test b = a;
Now, if we modify the data a, b also changes
Question 1:
When the assignment happens which function is called, is the MemberwiseClone()
of the System.object called
Question 2:
Test a = new Test();
Test b = (Test) a.Clone();
If you change the data of a , b doesn't change, it is because of the shallow copy.
Does MemberwiseClone()
creates new object and then does a copy?
Writing b = a
changes b
to refer to the same object that a
refers to.
Note that this is only true for classes; if a
and b
are structs, the value will be copied.
The MemberwiseClone
method returns a new object and assigns all of the fields in the new object to refer to the values from the original object.
That's a shallow copy.
From MSDN:
The MemberwiseClone method creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object.
MemberwiseClone()
creates a shallow copy, this has nothing to do with the assignment you do here though:
Test a = new Test();
Test b = a;
Both object references (a and b) point to the same object now. If you need MemberwiseClone()
you have to call it directly, just as you do in your Clone()
method.
精彩评论