What is the += / -= mean in a delegate data structure in c#?

倖福魔咒の 提交于 2019-12-11 16:46:28

问题


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?


回答1:


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.




回答2:


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

  • How to: Subscribe to and Unsubscribe from Events (C# Programming Guide)



回答3:


They are the compiler shorthand for adding and removing events.



来源:https://stackoverflow.com/questions/17935299/what-is-the-mean-in-a-delegate-data-structure-in-c

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