c# - 即使当前实例属于派生类,我们如何从基类中的另一个方法调用虚方法?

标签 c# derived-class base-class virtual-functions

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

我知道我们可以通过使用 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.

最佳答案

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

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

关于c# - 即使当前实例属于派生类,我们如何从基类中的另一个方法调用虚方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9922092/

相关文章:

c# - 调用 this() 构造函数和不同的 base() 构造函数

C# 将对象转换为基类列表

c# - 为什么我对 System.Threading.Timer 的使用不起作用?

javascript - 在 JavaScript 中操作数据时是否应该避免使用 C# 中的十进制类型

c++ - 从派生类构造函数调用基类构造函数

c++ - 指向基类数组的指针,用派生类填充

c# - 在 Windows 事件日志中检测手动时间更改和夏令时事件

c# - 迭代器 block 在 IL 中生成 try-fault

C++替换派生类中的基类

c++ - 在 C++ 中的模板化基类中查找名称