简体   繁体   English

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

[英]How do we call a virtual method from another method in the base class even when the current instance is of a derived-class?

How do we call a virtual method from another method in the base class even when the current instance is of a derived-class? 即使当前实例是派生类,我们如何从基类中的另一个方法调用虚方法?

I know we can call Method2 in the Base class from a method in the Derived class by using base.Method2() but what I want to do is calling it from the other virtual method in the Base class. 我知道我们可以从方法在派生类中,通过使用base.Method2(),但我想要做的就是从类中的其他虚拟方法调用它什么叫方法2中的类。 Is it possible? 可能吗?

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." );
    }
  }

}

With the above codes, it will output: 使用上面的代码,它将输出:

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

while what I would expect is: 而我期望的是:

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

No you cannot do that, the purpose of virtual methods is that derived classes can override the implementation and that the implementation is used even when called from base classes. 不,你不能这样做,虚方法的目的是派生类可以覆盖实现,甚至从基类调用时也使用实现。

If that causes problems then the code you need to run should not be in a virtual method. 如果这会导致问题,那么您需要运行的代码不应该是虚方法。

Obvious solution: 明显的解决方案:

    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();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM