public class data : ICloneable { public string m1; public object Clone() { return this.MemberwiseClone(); } } private data Fanzhuan_odd(data d) { data d2 = (data)d.Clone(); d2.m1 = "www"; }
浅拷贝是指将对象中的数值类型的字段拷贝到新的对象中,而对象中的引用型字段则指复制它的一个引用到目标对象。如果改变目标对象中引用型字段的值他将反映在原是对象中,也就是说原始对象中对应的字段也会发生变化。 Program { public class Sex { private string _PSex; public string PSex { set { _PSex = value; } get { return _PSex; } }
} public class Person : ICloneable { private Sex _pSex = new Sex(); public string pSex { set { _pSex.PSex = value; } get { return _pSex.PSex; } } private string _PName; public string PName { set { this._PName = value; } get { return this._PName; } } public void ShowPersonInfo() { } //浅拷贝 public object Clone() { return this.MemberwiseClone(); } //深拷贝 public object DeepClone() { Person newP = new Person(); newP.PName = this._PName; newP.pSex = this.pSex ; return newP; } } static void Main(string[] args) { } }
{ public string m1;
public object Clone()
{
return this.MemberwiseClone();
} }
private data Fanzhuan_odd(data d)
{
data d2 = (data)d.Clone();
d2.m1 = "www";
}
Program
{
public class Sex
{
private string _PSex;
public string PSex
{
set
{
_PSex = value;
}
get
{
return _PSex;
}
}
} public class Person : ICloneable
{
private Sex _pSex = new Sex();
public string pSex
{
set
{
_pSex.PSex = value;
}
get
{
return _pSex.PSex;
}
}
private string _PName;
public string PName
{
set
{
this._PName = value;
}
get
{
return this._PName;
}
} public void ShowPersonInfo()
{
}
//浅拷贝
public object Clone()
{
return this.MemberwiseClone();
}
//深拷贝
public object DeepClone()
{
Person newP = new Person();
newP.PName = this._PName;
newP.pSex = this.pSex ;
return newP;
} }
static void Main(string[] args)
{ }
}