Is it safe to unsubscribe from an event that has never been subscribed?

久未见 提交于 2019-12-18 21:49:13

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!