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

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


using System;
using System.Text;

namespace OverrideAndNew
{
  class Program
  {
    static void Main(string[] args)
    {
      BaseClass bc = new BaseClass();
      DerivedClass dc = new DerivedClass();
      BaseClass bcdc = new DerivedClass();

      // The following two calls do what you would expect. They call
      // the methods that are defined in BaseClass.
      bc.Method1();
      bc.Method2();
      // Output:
      // Base - Method1
      // Base - Method2


      // The following two calls do what you would expect. They call
      // the methods that are defined in DerivedClass.
      dc.Method1();
      dc.Method2();
      // Output:
      // Derived - Method1
      // Derived - Method2


      // The following two calls produce different results, depending 
      // on whether override (Method1) or new (Method2) is used.
      bcdc.Method1();
      bcdc.Method2();
      // Output:
      // Derived - Method1
      // Base - Method2
    }
  }

  class BaseClass
  {
    public virtual void Method1()
    {
      Console.WriteLine("Base - Method1");
    }

    public virtual void Method2()
    {
      Console.WriteLine("Base - Method2");
    }
  }

  class DerivedClass : BaseClass
  {
    public override void Method1()
    {
      Console.WriteLine("Derived - Method1");
    }

    public new void Method2()
    {
      Console.WriteLine("Derived - Method2");
    }
  }
}


以下示例显示了不同上下文中的类似行为。该示例定义了三个类:一个名为 Car 的基类,和两个由其派生的 ConvertibleCar 和 Minivan。基类中包含 DescribeCar 方法。该方法给出了对一辆车的基本描述,然后调用 ShowDetails 来提供其他的信息。这三个类中的每一个类都定义了 ShowDetails 方法。 new 修饰符用于定义 ConvertibleCar 类中的 ShowDetails。 override 修饰符用于定义 Minivan 类中的 ShowDetails。


// Define the base class, Car. The class defines two methods,
// DescribeCar and ShowDetails. DescribeCar calls ShowDetails, and each derived
// class also defines a ShowDetails method. The example tests which version of
// ShowDetails is selected, the base class method or the derived class method.
class Car
{
  public void DescribeCar()
  {
    System.Console.WriteLine("Four wheels and an engine.");
    ShowDetails();
  }

  public virtual void ShowDetails()
  {
    System.Console.WriteLine("Standard transportation.");
  }
}

// Define the derived classes.

// Class ConvertibleCar uses the new modifier to acknowledge that ShowDetails
// hides the base class method.
class ConvertibleCar : Car
{
  public new void ShowDetails()
  {
    System.Console.WriteLine("A roof that opens up.");
  }
}

// Class Minivan uses the override modifier to specify that ShowDetails
// extends the base class method.
class Minivan : Car
{
  public override void ShowDetails()
  {
    System.Console.WriteLine("Carries seven people.");
  }
}