【问题标题】:Does WithEvents in Visual Basic keep its EventHandlers when changing the reference to the object?更改对对象的引用时,Visual Basic 中的 WithEvents 是否保留其 EventHandlers?
【发布时间】:2013-02-26 10:18:53
【问题描述】:

在更改对对象的引用时,Visual Basic 中的WithEvents 是否保持其EventHandlers?

假设我声明了一个按钮,触发事件:

Private WithEvents _MyButton

现在我订阅了一个事件处理程序:

Private Sub _MyButton_Click() Handles _MyButton.Click 
  ' Here I DoClick()
End Sub

当我如下所示更改按钮对象的实例时,DoClick() 函数是否仍会被调用?

_MyButton = New Button()

【问题讨论】:

  • 我想:是的,但不确定...
  • 是的,它会的。设置引用后,将根据需要自动添加和/或删除处理程序。

标签: .net vb.net events event-handling handles


【解决方案1】:

这让我很好奇,所以我编写了一个小型控制台应用程序来可视化如果您使用计时器进行此实验会发生什么:

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 关键字。总之,答案是肯定的。

【讨论】:

    猜你喜欢
    • 2017-08-21
    • 1970-01-01
    • 2014-01-16
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-14
    相关资源
    最近更新 更多