简体   繁体   中英

What is the difference between normal and explicit implementation of events in C#

This is a normal implementation:

public event MyDelegate MyEvent; 

And this is explicit implementation:

private MyDelegate eventStorage
public event MyDelegate MyEvent
{
  add
  {
     eventStorage += value;
  }
  remove
  {
     eventStorage -= value;
  }
}

So, which implementation is more suitable and in which cases should I use each? Thanks for advice

The two examples are equivalent - the compiler would produce the second version (or similar) when compiling the first.

This is just syntactic sugar - use whichever one you are more comfortable with.

You can think of this as similar to what the compiler does with auto-implemented properties , only the other way around.

Normal will simply compile into something very similar to the explicit implementation anyway, if all it does is the subscription. The benefit with manual implementation is you have an opportunity to do something when someone subscribes or unsubscribes from the event.

The MSDN documentation demonstrates a sample use in Example 2.

Personally I've never need to break out an event manually in day-to-day activities. So for the vast majority of cases, the normal way is "more suitable" if you consider that it takes less code to express the same thing.

As soon as you want to do something like in the example, then not only is doing it explicitly "more suitable" it is actually required .

Only if the automatic implementation doesn't suit you you should use explicit.

For example WinForms events use explicit implementation to reduce the number of delegate fields on the class(there is one generated for each event) which are useless if nobody subscribes for the particular event, keeping a dictionary of delegates with one delegate for each event that someone ever subscribed to. That's just one case where this might be useful.

You can also log or apply security checks during subsription/removal of events.

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