我有这样的事情:
class BaseArg { }
class DerivedArg : BaseArg { }
interface IDoSomething
{
void DoSomething();
}
class A : IDoSomething
{
public BaseArg Value { get; set; }
public A(BaseArg value)
{
this.Value = value;
}
public static A Create(BaseArg arg)
{
return new A(arg);
}
public static B Create(DerivedArg arg)
{
return new B(arg);
}
public virtual void DoSomething()
{
}
}
class B : A
{
public DerivedArg DerivedValue { get; set; }
public B(DerivedArg value)
: base(value)
{
this.DerivedValue = value;
}
public override void DoSomething()
{
// does something different from A.DoSomething()
// uses additional stuff in DerivedArg
}
}
但是,即使我这样做:
DerivedArg arg = new DerivedArg();
A a = A.Create(arg);
A.Create(BaseArg arg)
被调用(因此A
被创建,这不是意图)。
我在这里错过了什么吗?如果是这样,我应该如何在不使用条件等奇怪的东西的情况下重写它arg as DerivedArg
。