在C#中是什么意思:通过事件使用-=运算符? [英] What does it means in C# : using -= operator by events?

查看:189
本文介绍了在C#中是什么意思:通过事件使用-=运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

何时必须通过事件使用此运算符?它的用途是什么?

When must we use this operator by events? What is its usage?

推荐答案

就像+ =为您订阅了该事件的处理程序一样,-=取消订阅了该事件.

Just as += subscribes you a handler to the event, -= unsubscribes it.

在引发事件时不再希望调用特定处理程序时使用它.您通常只需要使用它,引发事件的组件在逻辑上就比该事件的处理程序存在更长的时间-如果您不退订,事件引发器"实际上会引用该处理程序,因此可以使该处理程序的生存期长于你想要的.

Use it when you no longer want a particular handler to be called when the event is raised. You often only need to use it the component raising the event is logically longer lived than the handler of the event - if you don't unsubscribe, the "event raiser" effectively has a reference to the handler, so can keep it alive longer than you want.

如评论中所述:

  • -=将仅删除一个处理程序;如果订阅了多个处理程序(即使使用完全相同的委托),它仍只会将处理程序数减少1.指定处理程序的最后一个实例是已删除的那个. (因此,如果您以前有处理程序A,B,A,C以此顺序订阅并删除了A,那么最终将得到A,B,C.)
  • 如果指定的处理程序尚未订阅委托,则
  • -=不会导致错误;它只是忽略了请求.即使该事件此刻没有任何处理程序订阅,也是如此.
  • -= will only remove a single handler; if there are multiple handlers subscribed (even using the exact same delegate) it will still only reduce the handler count by 1. The last instance of the specified handler is the one removed. (So if you previously had handlers A, B, A, C subscribed in that order, and removed A, you'd end up with A, B, C.)
  • -= doesn't cause an error if the specified handler is not subscribed to the delegate already; it just ignores the request. This is true even if the event has no handlers subscribed to it at the moment.

这篇关于在C#中是什么意思:通过事件使用-=运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆