即使当前实例属于派生类,我们如何从基类中的另一个方法调用虚方法?
我知道我们可以通过使用 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/