如何删除所有事件处理程序?

时间:2013-02-22 23:40:55

标签: .net events c#-4.0 delegates

将事件设置为null是否可以有效地分离所有目标?

public class Test
{
    public delegate void SomethingHappenedEventHandler(Test obj);
    public event SomethingHappenedEventHandler SomethingHappened;

    private void OnSomethingHappened()
    {
        if (this.SomethingHappened != null)
            this.SomethingHappened(this);

        //Once this event is fired, do not allow any more invocations!
        this.SomethingHappened = null;
    }
}

而不必手动分离所有事件:

public class Thing
{
    priavte Test Testing { get; set; }

    public Thing()
    {
        this.Testing = new Test();
        this.Testing.SomethingHappened += DoSomething;
    }

    private void DoSomething(Test obj)
    {
        //Do some stuff.
        //Detach manually.
        this.Testing.SomethingHappened -= DoSomething;
    }
}

1 个答案:

答案 0 :(得分:2)

是的,null将有效地从列表中删除订阅者。您唯一需要记住的是,下次举起活动时,您可以获得NullReferenceException。因此,既然您正在检查not null的价值,那么您就可以了,但请务必在每次调用时进行检查。