我有两个数据类:BaseDataClass和DerivedDataClass,它们派生自第一个。我还有两个 Consuming 类:ConsumingBaseClass和ConsumingDerivedClass,它们派生自第一个。在ConsumingBaseClass我有虚拟方法DoWork,它接受DerivedDataClass并做一些工作。
在ConsumingDerivedClass中,我对方法DoWork进行了覆盖,并且对接受BaseDataClass的DoWork进行了重载。当我尝试调用DoWork时,传递DerivedDataClass的实例,调用DoWork(BaseDataClass)而不是DoWork(DerivedDataClass)。
有谁知道,为什么调用错误的方法?
以下代码演示了该问题:
class Program
{
private static void Main(string[] args)
{
ConsumingDerivedClass x = new ConsumingDerivedClass();
// Wrong DoWork is called - expected calling of DoWork(DerivedDataClass) but actually called DoWork(BaseDataClass)
x.DoWork(new DerivedDataClass());
Console.ReadKey();
}
}
public class ConsumingBaseClass
{
public virtual void DoWork(DerivedDataClass instance)
{
Console.WriteLine("ConsumingBaseClass.DoWork(DerivedDataClass); Type of argument is '{0}'", instance.GetType());
}
}
public class ConsumingDerivedClass : ConsumingBaseClass
{
public override void DoWork(DerivedDataClass instance)
{
Console.WriteLine("ConsumingDerivedClass.DoWork(DerivedDataClass); Type of argument is '{0}'", instance.GetType());
base.DoWork(instance);
// Some additional logic
}
public void DoWork(BaseDataClass instance)
{
Console.WriteLine("ConsumingDerivedClass.DoWork(BaseDataClass); Type of argument is '{0}'", instance.GetType());
DerivedDataClass derivedInstance = new DerivedDataClass();
// Some logic based on what is in baseInstacne
derivedInstance.SomeProperty = "Value, got from some logic";
base.DoWork(derivedInstance);
// Some additional logic
}
}
public class BaseDataClass
{ }
public class DerivedDataClass : BaseDataClass
{
public string SomeProperty { get; set; }
}