构建可克隆对象(ICloneable)

ContractedBlock.gif ExpandedBlockStart.gif 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();
        }
输出结果是一样的。

转载于:https://www.cnblogs.com/gisak/archive/2011/03/20/1989272.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值