What does it means in C# : using -= operator by ev

2020-08-26 11:18发布

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

5条回答
戒情不戒烟
2楼-- · 2020-08-26 11:35

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.
查看更多
等我变得足够好
3楼-- · 2020-08-26 11:36

Just as you can add event handlers via +=, you can remove them via -=.

For instance:

mybutton.Click += new EventHandler(myhandler);

You can later remove it like this:

mybutton.Click -= new EventHandler(myhandler);

...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 -=).

查看更多
4楼-- · 2020-08-26 11:41

The += and -= operators can be used in C# to add/remove event handlers to/from one of an object's events:

// adds myMethod as an event handler to the myButton.Click event
myButton.Click += myMethod;

After the above code runs, the myMethod method will be called every time myButton is clicked.

// removes the handler
myButton.Click -= myMethod;

After the above code runs, clicking on myButton will no longer cause myMethod to be called.

查看更多
何必那么认真
5楼-- · 2020-08-26 11:44

You remove the Eventhandler Function. C# Tutorial, Events and Delegates

查看更多
萌系小妹纸
6楼-- · 2020-08-26 12:00

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.

查看更多
登录 后发表回答