[英]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? -=
做什么?
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.