When must we use this operator by events? What is its usage?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
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.
As noted in comments:
-=
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.Just as you can add event handlers via
+=
, you can remove them via-=
.For instance:
You can later remove it like this:
...because event handlers for the same method and instance are equivalent (so you don't need to retain a reference to the handler you used with
+=
and use that one with-=
).The
+=
and-=
operators can be used in C# to add/remove event handlers to/from one of an object's events:After the above code runs, the
myMethod
method will be called every timemyButton
is clicked.After the above code runs, clicking on
myButton
will no longer causemyMethod
to be called.You remove the Eventhandler Function. C# Tutorial, Events and Delegates
I suspect that the background logic of the += is to add the handler to a list/array of event handlers for the given event. When -= is used, it compares your right hand argument to the list of event handlers it is holding for this event and deletes it from the list. If you do multiple += for a given event, each handler will get called.
Stated differently: += means add a method to the list of methods to call when the event occurs. -= means remove the specified method from the list of methods to call.
If all are removed, the event will have no handlers and the event will be ignored.