using System; using System.Collections.Generic; using System.Text; namespace WindowsApplication1 { public class ClassA:ICloneable { public int Value = 0; public object Clone() { return this.MemberwiseClone(); } } public class ClassB:ICloneable { public ClassA Member= new ClassA(); public object Clone() { //浅复制 //return this.MemberwiseClone(); //深复制 ClassB obj= new ClassB(); //obj.Member= (ClassA)Member.Clone(); return obj; } } public class class4 { public static void Main() { ClassB sb = new ClassB(); sb.Member.Value = 15; ClassB nb = (ClassB)sb.Clone(); nb.Member.Value = 6; Console.Write(sb.Member.Value.ToString() + “—” + nb.Member.Value.ToString()); ClassA nnb = new ClassA(); nnb.Value = 111; ClassA bbn = new ClassA(); bbn = (ClassA)nnb.Clone(); bbn.Value = 222; Console.Write(bbn.Value); Console.Read(); } } } 其中.MemberwiseClone()在上面已经介绍过了,通过实例可以清楚看到浅拷贝与深拷贝的区别
再来个:
using System; using System.Collections.Generic; using System.Text; namespace WindowsApplication1 { class 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 int aa = 1213; 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() { Console.WriteLine(“————————-“); Console.WriteLine(“Name:{0} Sex:{1}”, _PName, this.pSex); Console.WriteLine(“————————-“); Console.WriteLine(this.aa); } //浅拷贝 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) { Console.WriteLine(“原对象:”); Person p = new Person(); p.PName = “JackLee”; p.pSex = “男”; p.ShowPersonInfo(); //浅拷贝 Person copy = (Person)p.Clone(); //深拷贝 Person dcopy = (Person)p.DeepClone(); Console.WriteLine(“修改后的原对象:”); p.PName = “JackZhao”; p.pSex = “女”; p.aa = 1111; p.ShowPersonInfo(); Console.WriteLine(“修改后的浅拷贝对象:”); copy.ShowPersonInfo(); Console.WriteLine(“修改后的深拷贝对象:”); dcopy.ShowPersonInfo(); Console.WriteLine(“直接拷贝对象:”); Person PP = p; PP.ShowPersonInfo(); Console.ReadLine(); } } }
接下来介绍一下数组的拷贝:
首先数组的直接拷贝也就是复制,不用多说看例子:
int [] numbers = { 2, 3, 4, 5}; int [] numbersCopy = numbers; numbersCopy[2] = 0; Console.Write(numbers[2]); Console.Write(numbersCopy[2]);