如何才能知道如果一个特定的委托已经被分配给一个事件? [英] How do I find out if a particular delegate has already been assigned to an event?

查看:151
本文介绍了如何才能知道如果一个特定的委托已经被分配给一个事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个winform一个命令按钮。所以,如果我有这样的:

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

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



我怎么能知道任何特定的MyHandler的已经被添加到Click事件,因此它不获得再加入别的地方在我的代码?

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?

我读过如何使用GetInvocationList()为自己的事件的信息。但我试图让使用各种组合,我的命令按钮的项目时出错。它说,

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,

事件
'System.Windows.Forms.Control.Click'
只能出现在左侧$ b $的+ =或b - =

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

我缺少什么

- 我想强调的这个问题的艾哈迈德指出。这是一个杂牌组装电脑,应该是更容易恕我直言,但它看起来像它可能只是工作。

- 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.

推荐答案

如果您有疑问是,如果你的处理器已经加入则只是将其删除,然后重新添加。如果在第一个地方是不加处理程序,您的删除只是忽略

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;
}

这篇关于如何才能知道如果一个特定的委托已经被分配给一个事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆