简体   繁体   English

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

[英]Unsubscribing events in case variable closure

I'm always try to unsubscribe events where it possible and may. 我总是试图尽可能取消订阅事件。 In case when variable closure happen I do the following : 如果发生变量关闭,我会执行以下操作

int someVar;

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

moveStoryboard.Completed += moveCompleted;

But I don't want to use anonymous method and I think this is not good way. 但我不想使用匿名方法,我认为这不是好方法。 Please give me some advice or code samples. 请给我一些建议或代码示例。

Thanks in advance. 提前致谢。

If you don't want to use an anonymous function, it's much easier: 如果您不想使用匿名函数,则更容易:

moveStoryboard.Completed += HandleStoryboardCompleted;

...

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

That will actually create another instance of EventHandler each time the method is called, but because that instance will be equal to the one used to subscribe (same method with the same target) it will be fine to use for unsubscription. 这实际上会在每次调用方法时创建另一个EventHandler实例,但由于该实例将等于用于订阅的实例(具有相同目标的相同方法),因此可以用于取消订阅。

whats wrong with: 怎么错了:

class MyClass
{
    public event EventHandler MyEvent;

    public MyClass()
    {
        MyEvent += OnSomeEventHandlerToMyLocalClassWhichOfcourseIsABadPractice;
    }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM