How to Pass MethodName as Parameter of a Procedure in VBNET

[亡魂溺海] 提交于 2019-12-19 05:33:16

问题


I want to create a Procedure that its parameter is also a procedure. Is it possible?
I created some procedures to be used as parameters below:

Private Sub Jump(xStr as string)
    Msgbox xStr & " is jumping."
End Sub

Private Sub Run(xStr as string)
    Msgbox xStr & " is jumping."
End Sub

this procedure should call the procedure above:

Private Sub ExecuteProcedure(?, StringParameter) '- i do not know what to put in there
     ? ' - name of the procedure with parameter
End Sub

usage:

 ExecuteProcedure(Jump, "StringName")
 ExecuteProcedure(Run, "StringName")

回答1:


I believe the following code is an example for what you need.

Public Delegate Sub TestDelegate(ByVal result As TestResult)

Private Sub RunTest(ByVal testFunction As TestDelegate)

     Dim result As New TestResult
     result.startTime = DateTime.Now
     testFunction(result)
     result.endTime = DateTime.Now

End Sub

Private Sub MenuItemStartTests_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItemStartTests.Click

     Debug.WriteLine("Starting Tests...")
     Debug.WriteLine("")
     '==================================
     ' Add Calls to Test Modules Here

     RunTest(AddressOf Test1)
     RunTest(AddressOf Test2)

     '==================================

     Debug.WriteLine("")
     Debug.WriteLine("Tests Completed")

End Sub

The entire article can be found at http://dotnetref.blogspot.com/2007/07/passing-function-by-reference-in-vbnet.html

Hope this helps.



来源:https://stackoverflow.com/questions/8697504/how-to-pass-methodname-as-parameter-of-a-procedure-in-vbnet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!