问题
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. 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.
回答1:
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.
回答2:
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();
}
来源:https://stackoverflow.com/questions/9922092/how-do-we-call-a-virtual-method-from-another-method-in-the-base-class-even-when