Unsubscribing from anonymous delegate event

。_饼干妹妹 提交于 2019-12-06 13:38:34
Adam Houldsworth

Anonymous delegates are not guaranteed to be unique as created by the compiler, when unsubscribing this lack of uniqueness of the same code will cause it to fail to unsubscribe the correct handler. The only way to do so safely is to keep a reference to the delegate and use that to unsubscribe, or change it to a full method.

Delegates are equal based on object instance and method signature I believe.

A possible duplicate:

How to remove a lambda event handler

Basically, keep a reference:

MouseEventHandler handler = (sender, e) =>
        {
            Dragging = true;
            DragStart = new Point(e.X, e.Y);
            control.Capture = true;
        };

control.MouseDown += handler;
control.MouseDown -= handler;

Or turn the anonymous method into a proper method.

In short, you can not do that with anonymous delegate.

If you want to have a abbilty to unsubscribe from the event, define a delegate/action and follow a pattern you refer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!