我有一个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 ?
}
}
答案 0 :(得分:7)
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;
}
}
答案 1 :(得分:0)
答案 2 :(得分:0)
这是一种不使用处理程序变量的替代方法。
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 ...
}
}
}