简体   繁体   中英

When to Override OnEventMethod vs handling the actual event

Correct me if i'm wrong, but i believe most (if not all) classes in the CLR that raise events raise those events from protected methods, for example Form.OnMouseDown... so...

In a subclass, when would you want to override the "OnXyzMethod" instead of simple adding an event handler like Visual Studio does by default when you want to handle a controls event?

The only thing that occurs to me is that I might want to override the method to prevent the event from actually being raised... not that i can think of when that might apply...

The OnEvent method is provided in order to raise the event. This method is usually virtual so that you may change how and when the event is raised in a derived class. You should only override this method if you're changing either of those things.

If, for example, it wasn't appropriate to raise the event in a subclass under certain conditions (eg an object that is a disabled state), you could override the default OnEvent behaviour to prevent the event being raised.

You should not override the OnEvent method to add behaviour in response to the event occuring; that's the purpose of event handlers.

If in your derived class you want to do something that must happen before any event handlers run:

override void OnEvent(...)
{
    // ... my stuff that must execute before any event handlers
    base.OnEvent(...);
}

or that must happen after all event handlers are run:

override void OnEvent(...)
{
    base.OnEvent(...);
    // ... my stuff that must execute after any event handlers
}

or if you want to suppress the event, then override OnEvent .

If you are doing something that's independent of what other event handlers are doing, then just handle the event.

An example of where you might want to override is an event handler for an ASP.NET event (eg Load). When a WebForm loads, you might have code in the WebForm class that should run before (or after) the Load events of any UserControls it contains. In which case you might override OnLoad rather than handling the Load event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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