在变量闭包的情况下取消订阅事件

时间:2011-11-04 07:34:18

标签: c# c#-4.0 closures anonymous-methods

我总是试图尽可能取消订阅活动。 如果发生变量关闭,我会执行以下操作

int someVar;

EventHandler moveCompleted = null;
moveCompleted = delegate(object sender, EventArgs e)
{
    //...
    //here is variable closure
    someVar = 5;
    //...
    moveStoryboard.Completed -= moveCompleted;
};

moveStoryboard.Completed += moveCompleted;

但我不想使用匿名方法,我认为这不是好方法。 请给我一些建议或代码示例。

提前致谢。

2 个答案:

答案 0 :(得分:1)

如果您不想使用匿名函数,则更容易:

moveStoryboard.Completed += HandleStoryboardCompleted;

...

private void HandleStoryboardCompleted(object sender, EventArgs e)
{
    // Do stuff...
    moveStoryboard.Completed -= HandleStoryboardCompleted;
}

每次调用该方法时,实际上会创建EventHandler的另一个实例,但因为该实例将等于到用于订阅的实例(具有相同目标的相同方法)用于取消订阅会很好。

答案 1 :(得分:1)

错误:

class MyClass
{
    public event EventHandler MyEvent;

    public MyClass()
    {
        MyEvent += OnSomeEventHandlerToMyLocalClassWhichOfcourseIsABadPractice;
    }

    protected void OnSomeEventHandlerToMyLocalClassWhichOfcourseIsABadPractice(object sender, EventArgs e)
    {
        MyEvent -= OnSomeEventHandlerToMyLocalClassWhichOfcourseIsABadPractice;
    }
}