假设我有以下类层次结构(包括基本接口):
IAction -> (abstract) BaseAction -> (concrete) ImmediateAction -> (concrete) MovementAction
Run Code Online (Sandbox Code Playgroud)
现在,让我们说IAction公开了一个方法(嗯,实际上是IAction实现的不同接口,但让我们在这里保持简单!):
// Returns a new IAction instance deep copied from the current instance.
IAction DeepClone();
Run Code Online (Sandbox Code Playgroud)
目前很好?我们有深度复制方法,并且ImmediateAction有一些它想要复制的属性,因此它不仅提供实现DeepClone(),还提供复制构造函数:
//Base Action implementation
protected BaseAction(BaseAction old)
{
this.something = old.something;
}
//Immediate Action Implementation
protected ImmediateAction(ImmediateAction old)
: base(old)
{
this.anything = old.anything;
}
public IAction DeepClone()
{
return new ImmediateAction(this);
}
Run Code Online (Sandbox Code Playgroud)
现在,假设其中MovementAction没有任何与a相关的内容DeepClone(),因此它不实现方法或复制构造函数.
我遇到的问题是:
IAction x = new MovementAction();
IAction y = x.DeepClone();
//pleaseBeTrue is false
bool pleaseBeTrue = y is MovementAction;
Run Code Online (Sandbox Code Playgroud)
现在,我理解这里发生了什么 - MovementAction没有实现DeepClone(),所以ImmediateAction.DeepClone()被调用,实例化一个新的ImmediateAction.因此,y上述示例中的类型ImmediateAction代替MovementAction.
因此,在这个冗长的序言之后,我的问题是:对于这种情况,最佳做法是什么?我被困了?我是否只需要实现一个DeepClone()方法, 无论层次结构中的每个类都是什么?我在这里使用的模式是不正确的,还有更好的方法吗?
最后一点说明:如果可能的话,我想避免反思.
可以使用扩展方法并进行增量克隆
public static class DeepCopyExt
{
public static T DeepCopy<T>(this T item)
where T : ThingBase, new()
{
var newThing = new T();
item.CopyInto(newThing);
return newThing;
}
}
public abstract class ThingBase
{
public int A { get; set; }
public virtual void CopyInto(ThingBase target)
{
target.A = A;
}
}
public class ThingA : ThingBase
{
}
public class ThingB : ThingA
{
public int B { get; set; }
public override void CopyInto(ThingBase target)
{
var thingB = target as ThingB;
if(thingB == null)
{
throw new ArgumentException("target is not a ThingB");
}
thingB.B = B;
base.CopyInto(thingB);
}
}
class Program
{
static void Main(string[] args)
{
var b = new ThingB
{
A = 1,
B = 3
};
//c is ThingB
var c = b.DeepCopy();
var b1 = new ThingA
{
A = 1,
};
//c1 is ThingA
var c1 = b1.DeepCopy();
Debugger.Break();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1429 次 |
| 最近记录: |