简体   繁体   English

代表在VB.NET中

[英]Delegates in VB.NET

I am trying to use delegate concept to dynamically AddHandler to different events, ie instead of doing 我试图使用委托概念动态AddHandler到不同的事件,即而不是做

AddHandler tmrA.Elapsed, AddressOf tmrA_Tick
AddHandler tmrB.Elapsed, AddressOf tmrB_Tick


    Private Sub tmrA_Tick(ByVal sender As System.Object, ByVal e As System.Timers.ElapsedEventArgs)
' something here

    End Sub

    Private Sub tmrB_Tick(ByVal sender As System.Object, ByVal e As System.Timers.ElapsedEventArgs)
' something here

    End Sub

I was trying to do: 我试图这样做:

  Private Delegate Sub dlgtAB(ByVal sender As System.Object, ByVal e As System.Timers.ElapsedEventArgs)

and then 接着

Private Sub Test(ByRef tmr as Timer, dlgt as dlgtAB, intInterval as integer)
    tmr = New Timer(intInterval)
    AddHandler tmr.Elapsed, dlgtAB ' getting error right here on dlgtAB
End Sub

getting the following error: Error 15 Value of type 'dlgtAB' cannot be converted to 'System.Timers.ElapsedEventHandler'. 收到以下错误:错误15'dlgtAB'类型的值无法转换为'System.Timers.ElapsedEventHandler'。

can you tell me if this can be done and what is it that I am doing wrong 你能告诉我这是否可以做到,我做错了什么

Don't declare your own delegate type - use the ElapsedEventHandler type: 不要声明自己的委托类型 - 使用ElapsedEventHandler类型:

Private Sub Test(ByRef tmr as Timer, dlgt as ElapsedEventHandler, intInterval as integer)

This will allow you to assign the appropriate handler, as the types will match. 这将允许您分配适当的处理程序,因为类型将匹配。

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

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