Skip to main content
 首页 » 编程设计

c#之如何让基类调用它的虚函数

2024年02月06日8haluo1

例如,在下面的程序中,我希望 A 中的 entrypoint() 能够调用 A 中的 doThis code>,但它在 B 中调用 doThis,因为那是实例类型。我怎样才能实现我想要的?

void Main() 
{ 
    A a = new B(); 
    a.entrypoint(); 
} 
 
public class A 
{ 
    public void entrypoint() 
    { 
        this.doThis(); //doesn't call A::doThis() 
    } 
 
    public virtual void doThis() 
    { 
        Console.WriteLine ("From A"); 
    } 
} 
 
public class B : A 
{ 
    public override void doThis() 
    { 
        Console.WriteLine ("From B"); 
    } 
} 

编辑:How can I call the 'base implementation' of an overridden virtual method?是相似的,但我是从基类而不是 main 调用基实现。

编辑:类似于How do we call a virtual method from another method in the base class even when the current instance is of a derived-class?

请您参考如下方法:

正确的方法可以说是不调用虚拟方法,如果你需要它不被覆盖。我建议制作一个私有(private)方法来做你想做的事。