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

后端 未结 7 1651
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:45

    You can easily use a very simple approach here to not repeatedly subscribe to an event.

    Either of the 2 approaches below can be used:

    1. Flag approach : _getWarehouseForVendorCompletedSubscribed is a private variable initialized to false.

          if (!_getWarehouseForVendorCompletedSubscribed)
          {
              _serviceClient.GetWarehouseForVendorCompleted += new EventHandler<GetWarehouseForVendorCompletedEventArgs>(_serviceClient_GetWarehouseForVendorCompleted);
              _getWarehouseForVendorCompletedSubscribed = true;
          }
      
    2. Unsubscribe Approach :Include an unsubscribe everytime you want to subscribe.

      _serviceClient.GetWarehouseForVendorCompleted -= new 
          EventHandler<GetWarehouseForVendorCompletedEventArgs>  
       (_serviceClient_GetWarehouseForVendorCompleted);
      
      
      _serviceClient.GetWarehouseForVendorCompleted += new 
             EventHandler<GetWarehouseForVendorCompletedEventArgs>
             (_serviceClient_GetWarehouseForVendorCompleted);
      
    0 讨论(0)
提交回复
热议问题