假设我有一个静态类A
,它有一个静态事件:
public static class A
{
public static event Action SampleEvent;
//other members of A ...
}
我有一个静态类B
,它绑定到该事件:
public static class B
{
public static void DoSomeJob()
{
// To do some job, I need to bind to A.SampleEvent
// A.SampleEvent +=
// After the job is done, I still need the event handler, bound to A.SampleEvent, to update some thing in B
}
//other members of B ...
}
问题是,从A.SampleEvent
解除绑定的好地方是什么?不幸的是,静态类没有析构函数。
答案 0 :(得分:1)
更新B
之后,一个地方将直接在处理程序中:
public static class B
{
public static void DoSomeJob()
{
// To do some job, I need to bind to A.SampleEvent
A.SampleEvent += A_SampleEvent;
// do job
}
private static void A_SampleEvent(object sender, EventArgs args)
{
// update B
A.SampleEvent -= A_SampleEvent;
}
//other members of B ...
}