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

后端 未结 7 1649
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:38

    Publisher of the event implicitly overload only += and -= operations, and other operations are not implemented in the publisher because of the obvious reasons as explained above, such as don't want to give control to subscriber to change events.

    If we want to validate if a particular event is subscribed in the subscriber class, better publisher will set a flag in its class when event is subscriber and clear the flag when it is unsubscriber.

    If subscriber can access the flag of publisher, very easily identifiable whether the particular event is subscriber or not by checking the flag value.

提交回复
热议问题