Why don't events offer 3 access methods?

When implementing events, you can specify the code for the add and remove event handler. However, events can be accessed in three ways:

 MyEvent += Handler; // add accessor MyEvent -= Handler; // remove accessor MyEvent(this, EventArgs.Empty); // not supported by an accessor 

Wouldn't it be obvious that another accessor called invoke is responsible for this? My thoughts:

 class BaseClass { public virtual event EventHandler MyEvent { add; remove; protected invoke; } } class DerivedClass : BaseClass { public override event EventHandler MyEvent { invoke { // new code before event base.MyEvent(this, ...); // new code after event } } } 

I know an old style template that the OnMyEvent(...) method should implement. But there are two important drawbacks to this approach:

  • Event code scattered -> less organized code base
  • You cannot reorganize an event easily (for example, rename it)

Edit: Obviously, a compiler command already developed for this function (see GetRaiseMethod() ).

+4
source share
1 answer

This is on purpose, so that you do not trigger events that you do not “own”.

Edit (for editing an address): even in an inherited class, it is unclear whether you can always call it. Usually yes, and therefore the general template is well laid out:

  • Define an event (not a prefix with On )
  • Create a protected virtual method with the same name but with the On prefix, which accepts the corresponding EventArgs and simply performs a null check and call.
  • Always raise an event through a virtual method

This template provides more flexibility; You can change or omit events, or perform post-event processing by inheriting a method. If no method exists, the event call is private.

+5
source

All Articles