c# - 取消订阅匿名委托(delegate)事件

标签 c# events delegates anonymous

我在想出一种取消订阅一些匿名委托(delegate)事件的方法时遇到了一些麻烦,我在预制的帮助文件中找到了这些事件,这些文件有助于允许在运行时移动控件。我想取消订阅这些事件的原因是控件(在本例中为按钮)将再次被锁定并且无法移动。这是辅助类中的方法:

 public static void Init(Control control)
    {
        Init(control, Direction.Any);
    }

    public static void Init(Control control, Direction direction)
    {
        Init(control, control, direction);
    }

 public static void Init(Control control, Control container, Direction direction)
    {
        bool Dragging = false;
        Point DragStart = Point.Empty;

        control.MouseDown += delegate(object sender, MouseEventArgs e)
        {
            Dragging = true;
            DragStart = new Point(e.X, e.Y);
            control.Capture = true;
        };
        control.MouseUp += delegate(object sender, MouseEventArgs e)
        {
            Dragging = false;
            control.Capture = false;
        };
        control.MouseMove += delegate(object sender, MouseEventArgs e)
        {
            if (Dragging)
            {
                if (direction != Direction.Vertical)
                    container.Left = Math.Max(0, e.X + container.Left - DragStart.X);
                if (direction != Direction.Horizontal)
                    container.Top = Math.Max(0, e.Y + container.Top - DragStart.Y);
            }
        };

    }

下面是我如何通过调用方法订阅这些事件;

    ControlMover.Init(this.Controls["btn" + i]);

我已经在 MSDN 上阅读了一些关于取消订阅这些事件的方法,方法是创建一个保存这些事件的局部变量,然后通过这种方式取消订阅,但我似乎无法在我自己的项目中使用它。我该如何取消订阅这些事件,以便我的控件再次固定到位?

最佳答案

不保证匿名委托(delegate)在编译器创建时是唯一的,当取消订阅时,相同代码的这种缺乏唯一性将导致它无法取消订阅正确的处理程序。唯一安全地这样做的方法是保留对委托(delegate)的引用并使用它来取消订阅,或将其更改为完整方法。

我相信基于对象实例和方法签名,委托(delegate)是平等的。

可能重复:

How to remove a lambda event handler

基本上,保留一个引用:

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

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

或者把匿名方法变成一个合适的方法。

关于c# - 取消订阅匿名委托(delegate)事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10933328/

相关文章:

c# - 您如何使用盲人屏幕阅读器在 Visual C# 或 Visual Basic(均为 2010)速成版中对文本编辑器进行硬编码?

c# - 成就/徽章架构

c# - 使用 pinvoke 从 C# 代码调用时,非托管 C++ dll 何时从内存中卸载

c# - 复选框 CheckedChanged 事件

multithreading - SetEvent是原子的吗?

javascript - MSAnimationStart 事件在 IE10 上不起作用

c# - 为什么编译器在没有闭包的情况下为委托(delegate)添加额外的参数?

C# Visual Studio 截断 INSERT 查询中的字符串参数

ios - 通过委托(delegate)关闭其呈现的模态视图 Controller 后刷新 UIViewController 中的数据

c# - 可以在此通用代码中避免使用 Delegate.DynamicInvoke 吗?