How can I clear event subscriptions in C#?

前端 未结 10 1911
野趣味
野趣味 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 18:56

    From within the class, you can set the (hidden) variable to null. A null reference is the canonical way of representing an empty invocation list, effectively.

    From outside the class, you can't do this - events basically expose "subscribe" and "unsubscribe" and that's it.

    It's worth being aware of what field-like events are actually doing - they're creating a variable and an event at the same time. Within the class, you end up referencing the variable. From outside, you reference the event.

    See my article on events and delegates for more information.

提交回复
热议问题