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

后端 未结 4 1093
眼角桃花
眼角桃花 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 18:24

    The "plain" declaration for TypicalEvent does some compiler trickery. It creates an event metadata entry, add and remove methods and a backing field. When your code refers to TypicalEvent, the compiler translates it into a reference to the backing field; when external code refers to TypicalEvent (using += and -=), the compiler translates it into a reference to the add or remove method.

    The "explicit" declaration bypasses this compiler trickery. You are spelling out the add and remove methods and the backing field: indeed, as TcKs points out, there may not even be a backing field (this is a common reason for using the explicit form: see e.g. events in System.Windows.Forms.Control). Therefore the compiler can no longer quietly translate the reference to TypicalEvent into a reference to the backing field: if you want the backing field, the actual delegate object, you have to reference the backing field directly:

    _explicitEvent.RaiseEvent()
    

提交回复
热议问题