如何在VB NET中将方法名称作为过程的参数传递

时间:2012-01-02 04:53:07

标签: vb.net function methods parameter-passing

我想创建一个过程,其参数也是一个过程。可能吗? 我创建了一些程序用作以下参数:

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

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

此程序应调用上述程序:

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

用法:

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

1 个答案:

答案 0 :(得分:19)

我相信以下代码就是您需要的示例。

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

整篇文章可在http://dotnetref.blogspot.com/2007/07/passing-function-by-reference-in-vbnet.html

找到

希望这有帮助。