在现实生活中,我们将使用new为派生类中的虚拟方法提供新的实现的情况是什么? C#
我知道从技术上讲这意味着什么。我正在寻找的是一个现实生活中需要它的场景。
通过提供覆盖功能,我们总是可以实现相同的目的。当将方法调用强制转换为基数时,为什么要选择不正确的方法?
最佳答案
不,您无法达到相同目的。
// Define the base class
class Car
{
public virtual void DescribeCar()
{
System.Console.WriteLine("Four wheels and an engine.");
}
}
// Define the derived classes
class ConvertibleCar : Car
{
public new virtual void DescribeCar()
{
base.DescribeCar();
System.Console.WriteLine("A roof that opens up.");
}
}
class Minivan : Car
{
public override void DescribeCar()
{
base.DescribeCar();
System.Console.WriteLine("Carries seven people.");
}
}
现在,如果您尝试执行此操作:
public static void TestCars2()
{
Car[] cars = new Car[3];
cars[0] = new Car();
cars[1] = new ConvertibleCar();
cars[2] = new Minivan();
}
结果将是:
Car object: YourApplication.Car
Four wheels and an engine.
----------
Car object: YourApplication.ConvertibleCar
Four wheels and an engine.
----------
Car object: YourApplication.Minivan
Four wheels and an engine.
Carries seven people.
----------
覆盖始终在使用new作为其声明的类型(而不是基础类型)时才覆盖它。
你可以see more here
关于c# - 现实生活中使用new关键字隐藏虚拟方法的实现? C#,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6869427/