防止同样的事件处理函数分配多次 [英] Preventing same Event handler assignment multiple times

查看:140
本文介绍了防止同样的事件处理函数分配多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我分配在运行时的事件处理程序,它是在一个点可以被调用多次,有什么建​​议的做法,以防止同样的处理程序,以同一事件多次转让。

If I am assigning an event handler at runtime and it is in a spot that can be called multiple times, what is the recommended practice to prevent multiple assignments of the same handler to the same event.

object.Event += MyFunction

在一个将被调用不止一次将执行处理'N'次(当然)现货添加此。

Adding this in a spot that will be called more than once will execute the handler 'n' times (of course).

我已经使出删除以前的任何处理程序尝试通过

I have resorted to removing any previous handler before trying to add via

object.Event -= MyFunction; 

object.Event += MyFunction;

这工作,但不知何故似乎关闭。正确的处理任何建议;这种情况下的)

This works but seems off somehow. Any suggestions on proper handling ;) of this scenario.

推荐答案

Baget是正确的有关使用显式实现事件(尽管有一个混合显式接口实现和完整的事件语法)的存在。你也许可以不用它:

Baget is right about using an explicitly implemented event (although there's a mixture there of explicit interface implementation and the full event syntax). You can probably get away with this:

private EventHandler foo;

public event EventHandler Foo
{
    add
    {
        // First try to remove the handler, then re-add it
        foo -= value;
        foo += value;
    }
    remove
    {
        foo -= value;
    }
}

这可能有一些奇怪的边缘情况,如果你曾经添加或删除多播代表,但这是不可能的。它还需要小心文档,因为它不是正常事件的工作方式。

That may have some odd edge cases if you ever add or remove multicast delegates, but that's unlikely. It also needs careful documentation as it's not the way that events normally work.

这篇关于防止同样的事件处理函数分配多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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