C# virtual methods question

。_饼干妹妹 提交于 2019-12-24 03:05:10

问题


There is a thing I do not understand well: when virtual method is called, the base method is called as well?

Because when I use public override WinForm OnPaint method, in its body base.OnPaint(e) is called. I do not understand it, I thought virtual methods overrides the original one. If it is not usually called, why it is called in this case? Thank you


回答1:


when virtual method is called, the base method is called as well?

No.

Because when I use public override OnPaint(), in its body base.OnPaint(e) is called. I do not understand it, I thought virtual methods overrides the original one.

The developer chose to call base.OnPaint(e) and also do something else. In other words, the base implementation is something which you have at your hand in case it is useful to you - you can call it, and then do some additional specific work.

If the function body was only a call to the base, then it would be equivalent to not writing the overriding function at all.




回答2:


No, it is not called, if you don't call it explicitly from the derived class.




回答3:


I understand that, when you say "virtual method is called", you mean overriding method.

The answer is no. Whenever any version of the virtual method is called, it does not automatically call its base class methods. But sometimes you want to call them, so you include an explicit call to the base class method. Something like this:

class Base
{
  public virtual void VirtualMethod()
  {
    // Insert code here
  }
}

class Derived : Base
{
  public override void VirtualMethod()
  {
    // Insert code here
    base.VirtualMethod(); // Explicit call to the base class method
  }
}

If we had not included the instruction base.VirtualMethod();, the base class method would not be called when the derived class method is invoked.




回答4:


when virtual method is called, the base method is called as well?

This depends whether you call base.XXX in the overridden method or not.




回答5:


Sometimes you have code in the "base" method that is useful no matter which child method is being executed, then the children can just call the base method, but that's optional.

Unless you specifically call the base method, the child method gets called instead of the base rather than "as well as".



来源:https://stackoverflow.com/questions/3192967/c-sharp-virtual-methods-question

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!