Why do we need the “event” keyword while defining events?

后端 未结 6 1690
忘了有多久
忘了有多久 2020-11-29 17:43

I don\'t understand why do we need the \"event\" keyword while defining events, when we can do the same thing without using \"event\" keyword, just by using the delegates.

6条回答
  •  温柔的废话
    2020-11-29 18:32

    It's partly needed because if you omit the event keyword, it breaks encapsulation. If it's just a public multicast delegate, anyone can invoke it, set it to null or tamper with it. If a class called MailNotifier exists and it has an event called MailReceived, it makes no sense for other types to be able to fire that event via calling mailNotifier.MailReceived();

    On the other hand, you can only meddle with and invoke 'field like' events from the type that defined it.

    If you wanted to keep your event invocation private, there's nothing to stop you doing something like this:

    public class MyClassWithNonFieldLikeEvent
    {
       private CustomEventHandler m_delegate;
    
       public void Subscribe(CustomEventHandler handler) 
       {
          m_delegate += handler;        
       }
    
       public void Unsubscribe(CustomEventHandler handler)
       {          
          m_delegate -= handler;
       }
    
       private void DoSomethingThatRaisesEvent()
       {
          m_delegate.Invoke(...);
       }       
    }
    

    ... but that's a whole load of code just to (more or less) do what field-like events already give us.

提交回复
热议问题