How do I find out if a particular delegate has already been assigned to an event?

与世无争的帅哥 提交于 2019-12-30 17:21:42

问题


I have a command button on a winform. So, if I have something like:

myButton.Click += MyHandler1;
myButton.Click += MyHandler2;
myButton.Click += MyHandler3;

How can I tell if any particular MyHandler has already been added to the Click event so it doesn't get added again somewhere else in my code?

I've read how you can use GetInvocationList() for your own event's information. But I get errors when trying to get the items for my command button using various combinations. It says,

"The event 'System.Windows.Forms.Control.Click' can only appear on the left hand side of += or -=."

What am I missing?

[Edit] - I'd like to accentuate this question that Ahmad pointed out. It's a kludge and should be easier IMHO, but it looks like it might just work.


回答1:


If you're in doubt if your handler is already added then just remove it and add it again. If your handler wasn't added in the first place, your removal is just ignored.

myButton.Click -= MyHandler1;
myButton.Click += MyHandler1;

You could also create one method for attaching to an event, and make sure that the code is only run once.

private bool handlersAdded;
private void AddHandlers()
{
    if (this.handlersAdded) return;
    myButton.Click += MyHandler1;
    this.handlersAdded = true;
}



回答2:


The use of GetIvocationList can only be done from within the owner of the event (myButton in your case), that's one of the ideas behind events (as opposed to delegates).

Like Slugster said, you can't check the invocation list from outside myButton, but you can try and remove MyHandler# before adding it.



来源:https://stackoverflow.com/questions/4093442/how-do-i-find-out-if-a-particular-delegate-has-already-been-assigned-to-an-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!