【问题标题】:How to make base class call its virtual function?如何让基类调用它的虚函数?
【发布时间】:2014-07-15 03:20:09
【问题描述】:

例如在下面的程序中,我希望A 中的entrypoint() 能够在A 中调用doThis,但它在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? 类似,但我从基类而不是主类调用基实现。

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

【问题讨论】:

  • 如果在派生类中重写虚方法,只会调用被重写的方法。如果不重写,会调用基类方法
  • 如果要调用base中的函数,那么它不能是虚函数。

标签: c#


【解决方案1】:

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

【讨论】:

  • 私有化实际上对我有用,尽管我认为我的整个设计都依赖于虚函数。
  • 我不明白为什么有时调用基的版本没有用,而在所有其他情况下,派生对象的实现是默认的。例如,在 C++ 中,您只需使用基类的名称(甚至在基类的实现本身中),即代替 this.doThis() A::doThis()
  • @PeterSchneider 并不是说​​它永远不会有用,但它肯定有“代码味道”(en.wikipedia.org/wiki/Code_smell)。它只是在尖叫存在设计缺陷。
  • @itsme86 是的,人们应该肯定知道自己在做什么,就像经常一样。顺便说一句,可以利用托管 C++ 在 .net 中完成所需的工作:couldbedone.blogspot.de/2007/08/…,或反射,自然而然。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-28
  • 2012-04-01
  • 1970-01-01
  • 2021-09-05
  • 2010-10-14
  • 2013-01-02
相关资源
最近更新 更多