如何在类的Dispose方法中取消订阅匿名函数?

我有一个A类…在它的构造函数中…我正在为Object_B的eventHandler分配一个匿名函数。

如何从A类的Dispose方法中删除(取消订阅)?

任何帮助,将不胜感激 ! 谢谢

Public Class A { public A() { B_Object.DataLoaded += (sender, e) => { Line 1 Line 2 Line 3 Line 4 }; } Public override void Dispose() { // How do I unsubscribe the above subscribed anonymous function ? } } 

基本上你不能。 将其移动到方法中,或使用成员变量来保留委托以供以后使用:

 public class A : IDisposable { private readonly EventHandler handler; public A() { handler = (sender, e) => { Line 1 Line 2 Line 3 Line 4 }; B_Object.DataLoaded += handler; } public override void Dispose() { B_Object.DataLoaded -= handler; } } 

正确的方法是使用Rx扩展。 去观看video:

http://msdn.microsoft.com/en-us/data/gg577611

我发现“布鲁斯”电影特别有用。

这是一种不使用处理程序变量的替代方法。

 Public Class A { public A() { B_Object.DataLoaded += (sender, e) => { Line 1 Line 2 Line 3 Line 4 }; } Public override void Dispose() { if(B_Object.DataLoaded != null) { B_Object.DataLoaded -= (YourDelegateType)B_Object.DataLoaded.GetInvocationList().Last(); //if you are not sure that the last method is yours than you can keep an index //which is set in your ctor ... } } }