如何在C#中从Action委托中删除方法

如何在C#中从Action委托中删除方法

问题描述:


可能重复:

C#添加和删除匿名事件处理程序

假设我有这样声明的Action委托:

suppose I have an Action delegate declared this way:

public event Action<MenuTraverser.Actions> menuAction;

我正在以这种方式将方法与之关联:

I am associating a method to it this way:

menuInputController.menuAction += (MenuTraverser.Actions action) => this.traverser.OnMenuAction(action);

现在,一切正常,但是在某些情况下,我需要删除委托方法,但我不这样做不知道如何。
我尝试过这种方式,但是不起作用:

Now, all works fine, but in certain situation I need to remove the delegated method and I don't know how. I tried this way but doesn't work:

menuInputController.menuAction -= (MenuTraverser.Actions action) => this.traverser.OnMenuAction(action);

我该怎么做?我需要不再调用我的方法OnMenuAction。

How can I do such a thing? I need that my method OnMenuAction will be no longer called.

由于您的签名似乎匹配(假设您有一个 void 返回类型),则无需添加匿名函数,但可以直接使用方法组:

Since your signature seems to match (assuming that you have a void return type), you shouldn't need to add an anonymous function but you can use the method group directly:

menuInputController.menuAction += this.traverser.OnMenuAction;

在这种情况下,退订也应该有效:

And in this case unsubscribing should work as well:

menuInputController.menuAction -= this.traverser.OnMenuAction;