C#: event with explicity add/remove != typical event?

后端 未结 4 1088
眼角桃花
眼角桃花 2020-12-04 18:06

I have declared a generic event handler

public delegate void EventHandler();

to which I have added the extension method \'RaiseEvent\':

4条回答
  •  攒了一身酷
    2020-12-04 18:20

    When you create a "field-like" event, like this:

    public event EventHandler Foo;
    

    the compiler generates a field and an event. Within the source code of the class which declares the event, any time you refer to Foo the compiler understand that you're referring to the field. However, the field is private, so any time you refer to Foo from other classes, it refers to the event (and therefore the add/remove code).

    If you declare your own explicit add/remove code, you don't get an auto-generated field. So, you've only got an event, and you can't raise an event directly in C# - you can only invoke a delegate instance. An event isn't a delegate instance, it's just an add/remove pair.

    Now, your code contained this:

    public EventHandler TypicalEvent;
    

    This is slightly different still - it wasn't declaring an event at all - it was declaring a public field of the delegate type EventHandler. Anyone can invoke that, because the value is just a delegate instance. It's important to understand the difference between a field and an event. You should never write this kind of code, just as I'm sure you don't normally have public fields of other types such as string and int. Unfortunately it's an easy typo to make, and a relatively hard one to stop. You'd only spot it by noticing that the compiler was allowing you to assign or use the value from another class.

    See my article on events and delegates for more information.

提交回复
热议问题