开发者

elegant way of clearing an events

i am implementing a Buthon_Click Method, which as the name suggests is being used with an event onclick button.Now in order this method to do what i want i need to clear/unbind/unsubscribe the delegate attached to the SystemEvents.SessionSwitch event.The problem is that i want to do this without caring which method has been hooked up before. For an example:

SystemEvents.SessionSwitch += new SessionSwitchEventHandler(Methodx);

So what i am doing now is creating a foreach and going through all possibilities - 4 overall:

int [] array={1,2,3,4};


foreach (int n in array)
{
    SystemEvents.SessionSwitch -= new SessionSwitchEventHandler(SystemEvents_SessionSwitch1);
    SystemEvents.SessionSwitch -= new SessionSwitchEventHandler(SystemEvents_SessionSwitch2);
    SystemEvents.SessionSwitch -= new SessionSwitchEventHandler(SystemEvents_Ses开发者_如何转开发sionSwitch3);
    SystemEvents.SessionSwitch -= new SessionSwitchEventHandler(SystemEvents_SessionSwitch4);
}

i find this peace of code a bit cumbersome and awkward , and i was wondering if there is a more "elegant" way of doing this something like just SystemEvents.SessionSwitch == null or similar which would wipe out all methods hooked up ?

Thanks in advance


It depends who "owns" SystemEvents.SessionSwitch. In general, from outside you can't set the list of event handlers - you can only add or remove them. That's the level of encapsulation.

You should distinguish between events and any variable which may happen to be the backing store for an event. Events only support subscription and removal. See my article on events and delegates for more information.

Note that your existing code can be a little tidier already:

foreach (int n in array)
{
    SystemEvents.SessionSwitch -= SystemEvents_SessionSwitch1;
    SystemEvents.SessionSwitch -= SystemEvents_SessionSwitch2;
    SystemEvents.SessionSwitch -= SystemEvents_SessionSwitch3;
    SystemEvents.SessionSwitch -= SystemEvents_SessionSwitch4;
}

... although as you're not using n here, it's not really clear why you're looping.


One feature (among others) that sets events apart from delegates is this very restriction to += and -= only for outsiders. You cannot do any other operation on an event other then these two if you don't own the event.

The class that owns the event can ofcourse do :

SystemEvents.SessionSwitch==null; // only allowable to the owner of SessionSwitch
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜