即使当前实例是派生类的,我们如何从基类中的另一个方法调用虚拟方法

本文关键字:方法 基类 另一个 虚拟 调用 实例 派生 我们 | 更新日期: 2023-09-27 18:29:26

即使当前实例是派生类,我们如何从基类中的另一个方法调用虚拟方法?

我知道我们可以使用Base.Method2()Derived类中的方法调用Base中的Method2,但我想做的是从Base类中的另一个虚拟方法调用它。有可能吗?

using System;
namespace ConsoleApplication1
{
  class Program
  {
    static void Main( string[] args )
    {
      Base b = new Derived(  );
      b.Method1(  );
    }
  }

  public class Base
  {
    public virtual void Method1()
    {
      Console.WriteLine("Method1 in Base class.");
      this.Method2( );   // I want this line to always call Method2 in Base class, even if the current instance is a Derived object.
      // I want 'this' here to always refer to the Base class. Is it possible?
    }
    public virtual void Method2()
    {
      Console.WriteLine( "Method2 in Base class." );
    }
  }
  public class Derived : Base
  {
    public override void Method1()
    {
      Console.WriteLine( "Method1 in Derived class." );
      base.Method1();
    }
    public override void Method2()
    {
      Console.WriteLine( "Method2 in Derived class." );
    }
  }
}

使用以上代码,它将输出:

Method1 in Derived class.
Method1 in Base class.
Method2 in Derived class.

而我所期望的是:

Method1 in Derived class.
Method1 in Base class.
Method2 in Base class.

即使当前实例是派生类的,我们如何从基类中的另一个方法调用虚拟方法

不,不能这样做,虚拟方法的目的是派生类可以覆盖实现,并且即使从基类调用,也可以使用实现。

如果这会导致问题,那么需要运行的代码不应该在虚拟方法中。

明显的解决方案:

    public virtual void Method1()
    {
      Console.WriteLine("Method1 in Base class.");
      this.Method2Private( );
    }
    private void Method2Private()
    {
      Console.WriteLine( "Method2 in Base class." );
    }
    public virtual void Method2()
    {
      Method2Private();
    }