How can I clear event subscriptions in C#?

前端 未结 10 1923
野趣味
野趣味 2020-11-30 18:43

Take the following C# class:

c1 {
 event EventHandler someEvent;
}

If there are a lot of subscriptions to c1\'s someEven

10条回答
  •  孤街浪徒
    2020-11-30 18:51

    This is my solution:

    public class Foo : IDisposable
    {
        private event EventHandler _statusChanged;
        public event EventHandler StatusChanged
        {
            add
            {
                _statusChanged += value;
            }
            remove
            {
                _statusChanged -= value;
            }
        }
    
        public void Dispose()
        {
            _statusChanged = null;
        }
    }
    

    You need to call Dispose() or use using(new Foo()){/*...*/} pattern to unsubscribe all members of invocation list.

提交回复
热议问题