如何将子例程名称作为函数的参数传递?

时间:2013-04-18 03:16:32

标签: .net vb.net methods arguments argument-passing

我正在尝试创建一个泛型函数来创建线程,然后我需要将一个子例程名称传递给该函数,但我只能传递一个函数名称(这是无用的)。

我怎么能这样做?

有一种方法可以在不声明代理功能的情况下执行此操作吗? ......因为我说我会制作一个通用函数来简化事情。

这是我的代码:

Public Class Form1

' Desired usage:
' Make_Thread(Thread Variable, Thread Name, Thread Priority, Thread Sub)
'
' Example:
' Make_Thread(Thread_1, "Low thread", Threading.ThreadPriority.Low, AddressOf Test_Sub)

Private Thread_1 As Threading.Thread ' Thread Variable

Private Function Make_Thread(Of TKey)(ByRef Thread_Variable As Threading.Thread, _
                       ByVal Thread_Name As String, _
                       ByVal Thread_Priority As Threading.ThreadPriority, _
                       ByRef Thread_Sub As Func(Of String, TKey)) As Boolean ' I'd ByRef a function but really I will pass a Subroutine.

    ' See if the thread is already running.
    Dim is_running As Boolean
    If Thread_Variable Is Nothing Then _
         is_running = False _
    Else is_running = Thread_Variable.IsAlive

    ' If the thread is already running, do nothing.
    If is_running Then Return False : Exit Function

    ' Make the thread.
    Thread_Variable = New Threading.Thread(AddressOf Thread_Sub)
    Thread_Variable.Priority = Thread_Priority
    Thread_Variable.IsBackground = True
    Thread_Variable.Name = Thread_Name

    ' Start the thread.
    Thread_Variable.Start()
    Return True

End Function

Private Sub Test_Sub()
    MsgBox("A message from the thread!")
End Sub

End Class

0 个答案:

没有答案