How to remove a method from an Action delegate in C# [duplicate]

眉间皱痕 提交于 2019-12-08 03:00:24

问题


Possible Duplicate:
C# Adding and Removing Anonymous Event Handler

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);

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


回答1:


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;



回答2:


You need to store a reference to a generic delegate into a field so later you can unsubscribe using this cached delegate field:

// declare on a class fields level
Action<MenuTraverser.Action> cachedHandler; 

// in constructor initialize
cachedHandler = (action) => this.traverser.OnMenuAction(action);

// subscribe
menuInputController.menuAction += cachedHandler;

// unsubscribe
menuInputController.menuAction -= cachedHandler;


来源:https://stackoverflow.com/questions/8465239/how-to-remove-a-method-from-an-action-delegate-in-c-sharp

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