What is the += / -= mean in a delegate data struct

2019-09-14 21:58发布

If I have this code:

genetic = new Genetic();
genetic.foundNewBestGroupTour += new Genetico.NewBestGroupTourEventHandler(genetico_foundNewBestGroupTour);

What does the += do?

genetic.foundNewBestGroupTour -= new Genetico.NewBestGroupTourEventHandler(genetico_foundNewBestGroupTour);

What does the -= do?

3条回答
我命由我不由天
2楼-- · 2019-09-14 22:06

They are the compiler shorthand for adding and removing events.

查看更多
闹够了就滚
3楼-- · 2019-09-14 22:11

Read up on events.

The += operator in this context calls the event add accessor, while -= calls the remove accessor. This is usually called subscribing and unsubscribing to the event.

The usual way to implement an event is to have a backing field which holds a multicast delegate, in this case of type Genetico.NewBestGroupTourEventHandler. The accessors mentioned add and remove from the "invocation list" of this multicast delegate field.

查看更多
地球回转人心会变
4楼-- · 2019-09-14 22:12

It's used to subscribe / unsubscribe (bind / unbind) to an event.

genetic.foundNewBestGroupTour += genetico_foundNewBestGroupTour

Subscribes (binds) an event handler so that the method genetico_foundNewBestGroupTour will be called whenever the foundNewBestGroupTour event is raised on genetic.

genetic.foundNewBestGroupTour -= genetico_foundNewBestGroupTour;

Unsubscribes (unbinds) the handler. After this code is executed, the method genetico_foundNewBestGroupTour will be no longer be called when the foundNewBestGroupTour event is raised on genetic.

Further Reading

查看更多
登录 后发表回答