讀書釋疑--C#淺拷貝與深拷貝:
MemberwiseClone 方法建立一個淺表副本,方法是建立一個新對象,然後將當前對象的非靜態欄位複製到該新對象。如果欄位是實值型別的,則對該欄位執行逐位複製。如果欄位是參考型別,則複製引用但不複製引用的對象;因此,原始對象及其複本引用同一對象。
深拷貝,即實現ICloneable介面.ICloneable可用於深拷貝和淺拷貝
請看下面理解那句話.
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 A=this.MemberwiseClone() as InstanceA;
A.B=this.B.Copy();
return A; //深複製
// return (InstanceA)this.MemberwiseClone(); //淺複製
//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() as InstanceB;
}
}
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();
}
}