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

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

完成示例的方法 TestCars3 和 TestCars4。这些方法直接调用 ShowDetails,首先从宣布具有类型 ConvertibleCar 和 Minivan (TestCars3) 的对象调用,然后从具有类型 Car (TestCars4) 的对象调用。以下代码定义了这两种方法。


public static void TestCars3()
{
  System.Console.WriteLine("nTestCars3");
  System.Console.WriteLine("----------");
  ConvertibleCar car2 = new ConvertibleCar();
  Minivan car3 = new Minivan();
  car2.ShowDetails();
  car3.ShowDetails();
}

public static void TestCars4()
{
  System.Console.WriteLine("nTestCars4");
  System.Console.WriteLine("----------");
  Car car2 = new ConvertibleCar();
  Car car3 = new Minivan();
  car2.ShowDetails();
  car3.ShowDetails();
}

该方法产生下面的输出,它对应本主题中第一个示例的结果。


// TestCars3
// ----------
// A roof that opens up.
// Carries seven people.

// TestCars4
// ----------
// Standard transportation.
// Carries seven people.

以下代码显示了整个项目及其输出。


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OverrideAndNew2
{
  class Program
  {
    static void Main(string[] args)
    {
      // Declare objects of the derived classes and test which version
      // of ShowDetails is run, base or derived.
      TestCars1();

      // Declare objects of the base class, instantiated with the
      // derived classes, and repeat the tests.
      TestCars2();

      // Declare objects of the derived classes and call ShowDetails
      // directly.
      TestCars3();

      // Declare objects of the base class, instantiated with the
      // derived classes, and repeat the tests.
      TestCars4();
    }

    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
----------
Four wheels and an engine.
Standard transportation.
----------
Four wheels and an engine.
Standard transportation.
----------
Four wheels and an engine.
Carries seven people.
----------