开发者

Understanding AddHandler and pass delegates and events

开发者 https://www.devze.com 2022-12-23 12:53 出处:网络
I am using AddHandler to wire a function to a control\'s event that I dynamically create: Public Delegate Sub MyEventHandlerDelegate(ByVal sender As Object, ByVal e As System.EventArgs)

I am using AddHandler to wire a function to a control's event that I dynamically create:

Public Delegate Sub MyEventHandlerDelegate(ByVal sender As Object, ByVal e As System.EventArgs)

Public Sub BuildControl(EventHandler as System.Delegate)

         dim objMyButton as new button

         Ad开发者_如何学GodHandler objMyButton.Click, EventHandler

    end Sub

This code is generating a run-time exception stating:

Unable to cast object of type 'MyEventHandlerDelegate' to type 'System.EventHandler'

What am I not understanding about System.Delegate even though AddHandler takes as an argument of type "System.Delegate"? What Type does "EventHandler need to be to cast to a type that AddHandler can accept? Thanks for your help!


It sounds like the problem is that you are mixing types. The click event requires a System.EventHandler. Your custom delegate, although it has the same signature as System.EventHandler, is not a System.EventHandler.

So, you need to change your method take System.EventHandler instead of System.Delegate:

Public Sub BuildControl(EventHandler as System.EventHandler)
     dim objMyButton as new button
     AddHandler objMyButton.Click, EventHandler
End Sub


The delegate you are passing to BuildControl is of type MyEventHandlerDelegate. Could you show us the signature of that delegate? It could be that the signature of your delegate does not match the signature required by the Button.Click event.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号