Visual Basic中的WithEvents在更改对象的引用时是否保留其EventHandler?
说我已经宣布一个按钮,发射事件:
Private WithEvents _MyButton
现在我订阅了一个事件处理程序:
Private Sub _MyButton_Click() Handles _MyButton.Click ' Here I DoClick() End Sub
当我更改按钮对象的实例时,是否仍会调用DoClick()函数,如下所示?
_MyButton = New Button()
这让我很好奇,所以我写了一个小的控制台应用程序来想象如果你使用计时器做这个实验会发生什么:
Private WithEvents _t As New Timers.Timer With {.Enabled = True} Private Sub _t_Elapsed(sender As Object,e As Timers.ElapsedEventArgs) Handles _t.Elapsed Console.WriteLine("tick") End Sub Sub Main() ' let it tick for 5 seconds Task.Delay(5000).Wait() ' destroy the current timer Console.WriteLine("destroying this timer") _t.Dispose() _t = Nothing ' add a little pause Task.Delay(1000).Wait() ' create a new timer Console.WriteLine("creating a new timer") _t = New Timers.Timer With {.Enabled = True} ' let it tick for 5 seconds Task.Delay(5000).Wait() End Sub
如果运行此代码,您会发现在替换_t实例时确实附加了事件处理程序.我不知道它是如何做到的,但神奇的可能在于Handles关键字.无论如何,答案是肯定的.