关于浅拷贝和深拷贝的区别就不细说了(请参看下面代码).
通常会用到 深拷贝
代码 实现 如下:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 Person p = new Person { Name = new Name { FirstName = "Hua", LastName = "Rufus" }, Sex = Sex.Man }; 6 Person ptemp; 7 //ptemp = p; 普通赋值测试 8 //ptemp = p.Clone(); 浅拷贝 9 ptemp = p.DeepClone(); 10 ptemp.Name.FirstName = "xu"; 11 ptemp.Name.LastName = "ss"; 12 ptemp.Sex = Sex.Waman; 13 Console.WriteLine(p); 14 Console.WriteLine(ptemp); 15 Console.Read(); 16 } 17 } 18 19 [Serializable] 20 partial class Name 21 { 22 public string FirstName { get; set; } 23 24 public string LastName { get; set; } 25 26 public override string ToString() 27 { 28 return string.Format(" {0} {1}", LastName, FirstName); 29 } 30 31 } 32 33 [Serializable] 34 enum Sex 35 { 36 Man, 37 Waman 38 } 39 40 [Serializable] 41 partial class Person 42 { 43 public Name Name { get; set; } 44 45 public Sex Sex { get; set; } 46 47 public override string ToString() 48 { 49 return string.Format("name:{0} sex:{1}", Name, Sex.ToString()); 50 } 51 52 public Person Clone() 53 { 54 return this.MemberwiseClone() as Person; 55 } 56 57 public Person DeepClone() 58 { 59 using (MemoryStream ms=new MemoryStream()) 60 { 61 IFormatter formatter = new BinaryFormatter(); 62 formatter.Serialize(ms, this); 63 ms.Seek(0, SeekOrigin.Begin); 64 return formatter.Deserialize(ms) as Person; 65 } 66 } 67 68 69 }
主要代码:
1 using (MemoryStream memory=new MemoryStream()) 2 { 3 IFormatter formatter = new BinaryFormatter(); 4 formatter.Serialize(memory, this); 5 memory.Seek(0, SeekOrigin.Begin); 6 return formatter.Deserialize(memory); 7 }
还有一种方法 实现 深拷贝 (反射)http://www.codeproject.com/Articles/3441/Base-class-for-cloning-an-object-in-C
不过 这种方法太绕..而且只实现了 IList IDictionary 这种 内置类型