C# - 从Base转换为使用派生类方法

时间:2017-10-01 20:18:31

标签: c# casting

我有一个关于从Base转换到Derive Class方法的问题。这是我的代码:

class Vehicles
{
    public void SpecificRequiredTask()
    {
        Console.WriteLine("Base method");
    }
}

class Cars : Vehicles
{
    public new void SpecificRequiredTask()
    {
        Console.WriteLine("Derive method");
    }
}

class Program
{
    Vehicles car = new Cars();
    //I want to call the derive method, not base method, so that I do the 
    //casting
    ((Cars)car).SpecificRequiredTask();
}

问题是我的教授说“这不是必需的,因为你已经有了一个类型为Cars的物体。”但是我知道没有强制转换(Cars),程序仍会从Base类调用该方法。

如果不正确,请帮助我纠正我的理解。 谢谢

0 个答案:

没有答案