C#中Override关键字和New关键字的用法详解

2019-12-30 11:35:14丽君

该示例测试被调用的 ShowDetails 版本。以下方法,TestCars1 为每个类提供了一个实例,并在每个实例上调用 DescribeCar。


public static void TestCars1()
{
  System.Console.WriteLine("nTestCars1");
  System.Console.WriteLine("----------");

  Car car1 = new Car();
  car1.DescribeCar();
  System.Console.WriteLine("----------");


  // Notice the output from this test case. The new modifier is
  // used in the definition of ShowDetails in the ConvertibleCar
  // class. 

  ConvertibleCar car2 = new ConvertibleCar();
  car2.DescribeCar();
  System.Console.WriteLine("----------");

  Minivan car3 = new Minivan();
  car3.DescribeCar();
  System.Console.WriteLine("----------");
}


TestCars1 生成以下输出:尤其请注意 car2 的结果,该结果可能不是您所需的内容。对象的类型是 ConvertibleCar,但 DescribeCar 不会访问 ConvertibleCar 中定义的 ShowDetails 版本,因为方法已声明包含 new 修饰符,而不是 override 修饰符。因此,ConvertibleCar 对象显示与 Car 对象相同的说明。比较 car3 的结果,它是一个 Minivan 对象。在这种情况下,在 Minivan 类中声明的 ShowDetails 方法重写 Car 类中声明的 ShowDetails 方法,显示的说明描述微型面包车。


// TestCars1
// ----------
// Four wheels and an engine.
// Standard transportation.
// ----------
// Four wheels and an engine.
// Standard transportation.
// ----------
// Four wheels and an engine.
// Carries seven people.
// ----------

TestCars2 创建 Car 类型的对象列表。对象的值由 Car、ConvertibleCar 和 Minivan 类实例化而来。 DescribeCar 是调用列表中的每个元素。以下代码显示了 TestCars2 的定义。


public static void TestCars2()
{
  System.Console.WriteLine("nTestCars2");
  System.Console.WriteLine("----------");

  var cars = new List<Car> { new Car(), new ConvertibleCar(), 
    new Minivan() };

  foreach (var car in cars)
  {
    car.DescribeCar();
    System.Console.WriteLine("----------");
  }
}

显示以下输出。请注意,此输出与由 TestCars1 显示的输出相同。 ConvertibleCar 类的 ShowDetails 方法不被调用,无论对象的类型是 ConvertibleCar,如在 TestCars1 中,还是 Car,如在 TestCars2 中。相反,car3 在两种情况下都从 Minivan 类调用 ShowDetails 方法,无论它具有类型 Minivan 还是类型 Car。


// TestCars2
// ----------
// Four wheels and an engine.
// Standard transportation.
// ----------
// Four wheels and an engine.
// Standard transportation.
// ----------
// Four wheels and an engine.
// Carries seven people.
// ----------