简体   繁体   English

在派生类中使用基本方法的目的

[英]purpose of using base method in derived class

I'm looking at someone's code and has: 我正在查看某人的代码,并具有:

protected override void OnMouseEnter(MouseEventArgs e)
{
    base.OnMouseEnter(e);  //necessary?
    if (...)
}

Now, question is why base class method is called? 现在,问题是为什么要调用基类方法? this code would work without that anyway. 无论如何,此代码将无法工作。 any idea? 任何想法?

Thanks. 谢谢。 Amit 阿米特

The base calls are used when you want to utilize the functionality of the base's implementation yet want to extend what happens in the derived classes implementation. 当您想利用基础实现的功能但又想扩展派生类实现中发生的事情时,可以使用基础调用。

This can do some really useful things like setting up properties that are defined in the base class or handling events without having to put boilerplate code in each derived class. 这可以做一些非常有用的事情,例如设置基类中定义的属性或处理事件,而不必在每个派生类中放置样板代码。

由于基类方法具有默认行为,您可能仍要利用它。

Depending on the base class it might be necessary to also execute its method for it to function as intended. 根据基类,可能还必须执行其方法以使其按预期运行。 It's pretty much convention to call the base code as well as it might be important, especially if you do not know what it does. 调用基本代码非常惯例,因为它可能很重要,特别是如果您不知道它的作用的话。

It heavily depends on what you what the event handler to do. 这在很大程度上取决于您要处理的事件处理程序。 If your base class is complicated and it does a lot of things in OnMouseEnter() that you still want to keep, then you should have that base.OnMouseEnter(e) call. 如果您的基类很复杂,并且它在OnMouseEnter()中做了很多您想保留的事情,那么您应该调用base.OnMouseEnter(e) If you want to "override" the function completely, meaning you know what base.OnMouseEnter(e) does and you don't want it, then don't call base.OnMouseEnter(e) . 如果您想完全“覆盖”该函数,则意味着您知道base.OnMouseEnter(e)不想使用它,则不要调用base.OnMouseEnter(e)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM