简体   繁体   English

在c#中的委托数据结构中+ = /-=是什么意思?

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

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? -=做什么?

Read up on events . 阅读事件

The += operator in this context calls the event add accessor, while -= calls the remove accessor. 在这种情况下, +=运算符调用事件add访问器,而-=调用remove访问器。 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 . 实现事件的通常方法是拥有一个支持多播委托的后备字段,在这种情况下,该类型为Genetico.NewBestGroupTourEventHandler The accessors mentioned add and remove from the "invocation list" of this multicast delegate field. 提到的访问器在此多播委托字段的“调用列表”中添加和删除。

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 . 订阅(绑定)的事件处理程序,以便该方法genetico_foundNewBestGroupTour每当将被称为foundNewBestGroupTour事件上引发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 . 执行该代码后,该方法genetico_foundNewBestGroupTour将不再当被叫foundNewBestGroupTour上引发事件genetic

Further Reading 进一步阅读

它们是用于添加和删除事件的编译器简写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM