简体   繁体   English

接线和无线接线

[英]wiring and unwiring event

In some cases I have found, developers unwire event then wire it again like this: 在某些情况下,我发现,开发人员将无线事件再次连线,如下所示:

control.Click -= new eventHandler(eventHandler)
control.Click += new eventHandler(eventHandler)

why do they do that? 为什么他们这样做?

Possibly because there is other code in between that will trigger the event, and they don't want eventHandler to act on it. 可能是因为中间还有其他代码会触发事件,并且他们不希望eventHandler进行操作。 IMHO this isn't the best way to do things, but it's easy and it works. 恕我直言,这不是最好的做事方式,但它很容易,而且很有效。

If there is no other code in between there cannot possibly be a reason to remove and add the same event handler again. 如果中间没有其他代码,则可能无法再次删除和添加相同的事件处理程序。

I can explain this in a simple screnerio. 我可以用一个简单的screnerio来解释这个。

Imagine you have a "button1" And you added the event on the run-time. 想象一下,您有一个“button1”并且您在运行时添加了该事件。

But once this button is clicked. 但是一旦点击了这个按钮。 The process behind it take let say "3Mins" to complete. 它背后的过程需要说“3Mins”来完成。 And you don't want the user to click this button again. 而且您不希望用户再次单击此按钮。

So you can do by Unwiring it in the first time. 所以你可以通过第一次解开它来做。 So that the person don't click the button again and again. 这样人就不会一次又一次地点击按钮。 And adding the instruction in the queue. 并在队列中添加指令。

If you call code that wires an event, and you don't wont to accidentally wire it up again if it was already wired, you can unwire, and then rewire it. 如果您调用连接事件的代码,并且如果已经连线,则不会意外地将其连接起来,您可以取消连接,然后重新连接。 This is the code sample above. 这是上面的代码示例。

If it wasn't already wired in the first place, no error is thrown. 如果它首先没有连接,则不会抛出任何错误。 But if the code had already been run first, you don't wont the event to run twice. 但是如果代码已经先运行过,那么你不会让事件运行两次。 Thus, unwire and then rewire. 因此,unwire然后重新连接。

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

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