上述答案是正確的;我只想做一個筆記。如果您保留對委託/ lambda的其他引用,那麼用作處理程序的匿名委託只能取消訂閱。這是因爲lambda表達式是「函數文本」,有點像字符串常量,但是不像串確定的平等時,他們沒有比較語義:
public event EventHandler MyEvent;
...
//adds a reference to this named method in the context of the current instance
MyEvent += Foo;
//Adds a reference to this anonymous function literal to MyEvent
MyEvent += (s,e) => Bar();
...
//The named method of the current instance will be the same reference
//as the named method.
MyEvent -= Foo;
//HOWEVER, even though this lambda is semantically equal to the anonymous handler,
//it is a different function literal and therefore a different reference,
//which will not match the anonymous handler.
MyEvent -= (s,e) => Bar();
var hasNoHandlers = MyEvent == null; //false
//To successfully unsubscribe a lambda, you have to keep a reference handy:
EventHandler myHandler = (s,e) => Bar();
MyEvent += myHandler;
...
//the variable holds the same reference we added to the event earlier,
//so THIS call will remove the handler.
MyEvent -= myHandler;
是否存在的「弱引用事件」以任何標準形式/成語? – 2011-02-22 18:21:25