如何查明某个特定代表是否已被分配给某个活动?

发布于 2024-09-30 16:47:14 字数 572 浏览 0 评论 0原文

我在 winform 上有一个命令按钮。因此,如果我有类似的情况:

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

如何判断任何特定的 MyHandler 是否已添加到 Click 事件中,以便它不会再次添加到代码中的其他位置?

我已阅读如何使用 GetInitationList() 获取您自己的事件信息。但是,当尝试使用各种组合获取命令按钮的项目时,我收到错误。它说,

“活动 '系统.Windows.Forms.Control.Click' 只能出现在左侧 += 或 -=。”

我错过了什么?

[编辑] - 我想强调 艾哈迈德指出的这个问题。这是一个拼凑,恕我直言,应该更容易,但看起来它可能会起作用。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

瑾夏年华 2024-10-07 16:47:14

如果您不确定您的处理程序是否已添加,只需将其删除并重新添加即可。如果您的处理程序最初没有添加,您的删除将被忽略。

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

您还可以创建一种方法来附加到事件,并确保代码仅运行一次。

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

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;
}
蓝颜夕 2024-10-07 16:47:14

GetI VocationList 的使用只能在事件的所有者(在您的例子中为 myButton)内完成,这是事件背后的想法之一(与委托相对)。

就像 Slugster 所说,您无法从 myButton 外部检查调用列表,但您可以在添加之前尝试删除 MyHandler#。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文