如何取消订阅类的 Dispose 方法中的匿名函数? [英] How to unsubscribe an anonymous function in Dispose method of a class?
本文介绍了如何取消订阅类的 Dispose 方法中的匿名函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 A 类......在它的构造函数中......我正在为 Object_B 的 eventHandler 分配一个匿名函数.
I have a Class A...in it's constructor...I am assigning an anonymous function to Object_B's eventHandler.
如何从 A 类的 Dispose 方法中删除(取消订阅)它?
How do I remove (unsubscribe) that from Dispose method of class A ?
任何帮助将不胜感激!谢谢
Any help would be appreciated ! Thanks
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 ?
}
}
推荐答案
基本上你不能.要么将其移动到方法中,要么使用成员变量来保留委托以备后用:
You can't, basically. Either move it into a method, or use a member variable to keep the delegate for later:
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;
}
}
这篇关于如何取消订阅类的 Dispose 方法中的匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文