Pregunta

C# has events built in with a keyword. So if you want to declare an event, you write:

public event MyEventHandler SomethingHappened;

It is convenient, as it does allow you to add multiple event handlers, although it also prevents you from customising how events are handled, such as if you want to ensure that certain event handlers would always run in a certain order.

It seems that code would be more flexible if it was instead written as:

public Event<MyEventHandler> SomethingHappened = default;

Then you could also substitute in custom events. I also see no reason why the += operation couldn't still be used for adding new handlers. So does this simply decrease flexibility or does the keyword offer anything else?

¿Fue útil?

Solución

The point of an event is that it doesn't allow outsiders to get or overwrite all event handlers. An event essentially a specialized kind of property, which has add/remove instead of get/set.

The version you show is the analog of an auto-property. If you're not content with the default implementation of add/remove, write your own.

public event EventHandler MyEvent {
   add { ... } 
   remove { ... }
}

Events have nothing to do with allowing to add you multiple handlers, you can already do that using multicast delegates.

Otros consejos

The main value of an event being a first class citizen in the .NET world (that I can think of) is that it is recognizable through reflection across language implementations. This allows one developer to create a full featured (possibly closed source) component and have another developer use it.

Events are mainly a component feature that allow interaction between pieces of software with minimum dependencies. This is also the reason for the standard handler prototype: (object sender, EventArgs e).

If this feels too restrictive and you do not care about unknown client or this scenario just does not apply to your situation, you can still create your own mechanism. But any developer that has to maintain your stuff after you will hate you for it.

Licenciado bajo: CC-BY-SA con atribución
scroll top