学习.NET (8) 实现派生类中Deep Copy的几种常用方法(通过ICloneable接口)

By Alva Chien
2008.10.03

跟C++编译器会默认提供一个Copy Constructor函数不同,C#中回避了这个问题。跟System.Object提供了一个充满歧义的Equals方法一样,System.Object还提供了一个MemberwiseClone方法,但是这个方法的名字依旧带来不小的误解,其实,这个函数只是实现了Shallow Copy,对.NET CLR中占绝大多数的Heap中使用的Reference Type,该函数只是复制了指针。

FCL提供了ICloneable接口,该接口只有一个Method:Clone(),返回值为System.Object。通过实现这个接口,该对象被认为是可以被Clone的,也就是可以被Copy的。至于是Deep Copy还是Shallow Copy就完全依赖于Clone方法是如何被实现了。

这里,遇到的第一个问题就是,当数个类之间有派生关系时,如何实现Deep Copy?

第一种方法,就是只在基类中实现ICloneable接口,并创建一个新的virtual方法,并在Clone方法中调用该virtual方法,所有的派生类只需要override这个virtual方法即可。

class Base : ICloneable
{
protected Int32 nBase = default(Int32);
public Object Clone()
{ return RealClone(null); }
protected virtual Object RealClone(Object obj)
{
if (obj == null) obj = new Base();
((Base)obj).nBase = this.nBase;
return obj;
}
}
class Derived : Base
{
protect Byte byDrv = default(Byte);
protected override Object RealClone(Object obj)
{
if (obj == null) obj = new Derived();
base.RealClone(obj);
((Derived)obj).byDrv = this.byDrv;
return obj;
}
}

第二种方法,为Base和Derived类都指定ICloneable接口。

class Base : ICloneable
{
protected Int32 nBase = default(Int32);
protected virtual Object Clone()
{
Base obj = new Base();
obj.nBase = this.nBase;
return obj;
}
}
class Derived : Base, ICloneable
{
protect Byte byDrv = default(Byte);
protected override Object Clone()
{
Derived obj = (Derived)base.Clone();
obj.byDrv = this.byDrv;
return obj;
}
}

第三种方法,采用类似C++的解决方案,为每个class实现一个Copy Constructor——即一个接受该类实例的Constructor。与第二种方法一样,同样为每个Class实现ICloneable方法。

class Base : ICloneable
{
protected Int32 nBase = default(Int32);
protected Base(Base other)
{ this.nBase = other.nBase; }
Object ICloneable.Clone()
{ return new Base(this); }
}
class Derived : Base, ICloneable
{
protect Byte byDrv = default(Byte);
protected Derived(Derived other) : base(other)
{ this.byDrv = other.byDrv; }
Object ICloneable.Clone()
{ return new Derived(this); }
}

好了,有了以上办法,可以创建支持Deep Copy的派生类了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值