In C#, why can't I test if a event handler is null anywhere outside of the class that it's defined?

后端 未结 7 1667
Happy的楠姐
Happy的楠姐 2020-12-24 05:58

I am sure that I am just not understanding something fundamental about events and/or delegates in C#, but why can\'t I do the Boolean tests in this code sample:



        
7条回答
  •  醉酒成梦
    2020-12-24 06:26

    It's a rule in place when using the 'event' keyword. When you create an event, you are restricting outside class interaction with the delegate to a "subscribe / unsubscribe" relationship, this includes cases of inheritance. Remember an event is essentially a property, but for method calls, it isn't really an object itself, so really it looks more like this:

    public event SomeEventHandler SomeEvent
    {
         add
         {
              //Add method call to delegate
         }
         remove
         {
              //Remove method call to delegate
         }
    }
    

提交回复
热议问题