解除静态事件处理程序的位置?

时间:2015-01-27 13:06:35

标签: c# .net events static

假设我有一个静态类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解除绑定的好地方是什么?不幸的是,静态类没有析构函数。

1 个答案:

答案 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 ...
}