构建可克隆对象(ICloneable)

View Code
public class Point
{
public int x, y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public override string ToString()
{
return string.Format("X={0},Y={1}", x, y);
}
}
class Program
{
static void Main(string[] args)
{
Point p1
= new Point(50, 12);
Point p2
= p1;
p2.x
= 0;
Console.WriteLine(p1.ToString());
Console.WriteLine(p2.ToString());
Console.ReadLine();
}
}

   输出结果:X=0,Y=12

                 X=0,Y=12

上面的复值操作将两个引用指向堆上的同一个Point对象,通过任何一个引用都可以修改堆上的同样对象(引用类型)如果对上面的代码小小的修改下:

public class Point
{
public int x, y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public override string ToString()
{
return string.Format("X={0},Y={1}", x, y);
}
public object Clone()
{
return new Point(this.x, this.y);// 返回一个当前对象的副本
}
}
class Program
{
static void Main(string[] args)
{
Point p1
= new Point(50, 12);
Point p2
= (Point)p1.Clone();//这里需要通过显示转换
p2.x = 0;
Console.WriteLine(p1.ToString());
Console.WriteLine(p2.ToString());
Console.ReadLine();
}
}
输出结果变为:X=50,Y=12

                    X=0,Y=12

因为Point类型并不包含引用类型变量,可以进一步简化Clone()方法的实现

 public object Clone()
        {
            return this.MemberwiseClone();
        }
输出结果是一样的。
posted @ 2011-03-20 10:47  师士  阅读(286)  评论(0编辑  收藏  举报