读书释疑--C#浅拷贝与深拷贝
读书释疑--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();
}
}
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();
}
}