关于浅拷贝和深拷贝的区别就不细说了(请参看下面代码).

通常会用到 深拷贝

代码 实现 如下:

 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     }
View Code

相关文章:

  • 2022-12-23
  • 2021-07-18
  • 2021-06-17
  • 2021-09-27
  • 2022-02-21
  • 2021-07-14
  • 2021-07-17
  • 2022-12-23
猜你喜欢
  • 2021-10-11
  • 2022-12-23
  • 2021-12-27
  • 2022-12-23
  • 2022-12-23
  • 2022-01-01
相关资源
相似解决方案