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

后端 未结 4 1091
眼角桃花
眼角桃花 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:32

    That's because you're not looking at it right. The logic is the same as in Properties. Once you've set the add/remove it's no longer an actual event, but a wrapper to expose the actual event (events can only be triggered from inside the class itself, so you always have access locally to the real event).

    private EventHandler _explicitEvent;
    public event EventHandler ExplicitEvent {
       add { _explicitEvent += value; } 
       remove { _explicitEvent -= value; }
    }
    
    private double seconds; 
    public double Hours
    {
        get { return seconds / 3600; }
        set { seconds = value * 3600; }
    }
    

    In both cases the member with the get/set or add/remove property doesn't really contain any data. You need a "real" private member to contain the actual data. The properties just allow you program extra logic when exposing the members to outside world.

    A good example for WHY you'd want to do it, is to stop extra computation when it's not needed (no one is listening to the event).

    For example, lets say the events are triggered by a timer, and we don't want the timer to work if no-one is registered to the event:

    private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
    private EventHandler _explicitEvent;
    public event EventHandler ExplicitEvent 
    {
       add 
       { 
           if (_explicitEvent == null) timer.Start();
           _explicitEvent += value; 
       } 
       remove 
       { 
          _explicitEvent -= value; 
          if (_explicitEvent == null) timer.Stop();
       }
    }
    

    You'd probably want to lock the add/remove with an object (an afterthought)...

提交回复
热议问题