For example, if these codes:
Button button1 = new Button();
// ...
button1.Click -= button1_Clicked;
are executed before:
button1.Click += button1_Clicked;
I found no error or exception, but I am wondering if there is any downside here.
If it is safe, why is it allowed to unsubscribe from an event that has never been subscribed?
I can't find a reference specific to events, but it is documented for the underlying function that events use, Delegate.Remove
:
Returns source if value is null or if the invocation list of value is not found within the invocation list of source
So it will be safe at least for events that use implicit accessors.
Custom accessors are a whole other ball of wax, as one could implement the remove
block however you want. I would assume people would mimic the implicit behavior, but this isn't enforced.
来源:https://stackoverflow.com/questions/25678172/is-it-safe-to-unsubscribe-from-an-event-that-has-never-been-subscribed