码迷,mamicode.com
首页 > 其他好文 > 详细

克隆示例

时间:2015-05-01 11:52:03      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:

值类型使用基于值的语法,结构(也包括所有数值数据类型int,float等,以及任何枚举或自定义结构)。

如果有一个仅包含值类型的类或结构,使用MemberwiseClone()实现Clone()方法。如果有一个保存其他引用类型的自定义类型,需要建立一个考虑了每个引用类型成员变量的新对象。

 1 // 该类定义了一个点
 2     public class PointDescription
 3     {
 4         public string PetName { get; set; }
 5         public Guid PointID { get; set; }
 6 
 7         public PointDescription()
 8         {
 9             PetName = "No-name";
10             PointID = Guid.NewGuid();
11         }
12     }

 

 1 public class Point : ICloneable
 2     {
 3         public int X { get; set; }
 4         public int Y { get; set; }
 5         public PointDescription desc = new PointDescription();
 6 
 7         public Point( int xPos, int yPos, string petName )
 8         {
 9             X = xPos; Y = yPos;
10             desc.PetName = petName;
11         }
12         public Point( int xPos, int yPos )
13         {
14             X = xPos; Y = yPos;
15         }
16         public Point() { }
17 
18         // 重写 Object.ToString().
19         public override string ToString()
20         {
21             return string.Format("X = {0}; Y = {1}; Name = {2};\nID = {3}\n",
22             X, Y, desc.PetName, desc.PointID);
23         }
24 
25         // 需要调整 PointDescription成员
26         public object Clone()
27         {
28             // 获取浅复制
29             Point newPoint = (Point)this.MemberwiseClone();
30 
31             // 填充间距
32             PointDescription currentDesc = new PointDescription();
33             currentDesc.PetName = this.desc.PetName;
34             newPoint.desc = currentDesc;
35             return newPoint;
36         }
37     }

 

Point p3 = new Point(100, 100, "Jane");
Point p4 = (Point)p3.Clone();
这样返回自Clone()的Point复制了它的内部引用类型成员变量,而不是在内存中“指向”同样的对象。

克隆示例

标签:

原文地址:http://www.cnblogs.com/ht-beyond/p/4470486.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!