C# - Event keyword advantages?

前端 未结 3 1001
Happy的楠姐
Happy的楠姐 2020-12-05 02:47

I\'ve come to recently understand that a C# \'event\' really is. It isn\'t really anything, honestly. To sum up my findings: The event keyword is simply a m

3条回答
  •  臣服心动
    2020-12-05 03:00

    Basically, I wanted the derived classes to use these events as their own. The only way to do this was to expose the backing variable of the events as protected, so the derived classes could raise the events.

    The usual way to handle this is not to expose the field, but to expose a method to raise the event.

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) {
      var handler = PropertyChanged;
      if (handler != null)
        handler(this, e);
    }
    

    This not only allows derived classes to raise the event, but also allows derived classes to do something before any subscribed handlers actually get called.

    To answer your actual question, though:

    What is the advantage of using the event keyword other than for modifying how the delegate can be accessed?

    One advantage not yet mentioned (I think):

    public event PropertyChangedEventHandler PropertyChanged;
    

    can be changed to

    public event PropertyChangedEventHandler PropertyChanged
    {
      add { /* custom code here */ }
      remove { /* custom code here */ }
    }
    

    without requiring a recompile of all users of your library. You might want something like this if you later find a reason to not simply store the handlers in a private field. This is the same advantage of an auto-implemented property over a field.

提交回复
热议问题