我想知道是否有可能通過名稱而不是明確地實例化和調用委託。我認爲下面的代碼很好地解釋了它....我想接受一個函數名稱,然後基於此實例化委託。在這個例子中,我使用了一個select case,但是我想消除它,只使用methodName參數本身。可能通過名稱實例化和調用委託?
恭敬地......請避免衝動告訴我這是瘋了,我應該採取一些完全不同的方法來做到這一點。 :)
Private Delegate Sub myDelegate()
Private Sub myDelegate_Implementation1()
'Some code
End Sub
Private Sub myDelegate_Implementation2()
'Some code
End Sub
Public Sub InvokeMethod(ByVal methodName As String)
Dim func As myDelegate = Nothing
'??? HOW TO GET RID OF THIS SELECT CASE BLOCK?:
Select Case methodName
Case "myDelegate_Implementation1"
func = AddressOf myDelegate_Implementation1
Case "myDelegate_Implementation2"
func = AddressOf myDelegate_Implementation2
End Select
func.Invoke()
End Sub
感謝基思,正是我在找什麼。 (儘管BFree的方法在大多數情況下也可以工作)。
這裏是工作的代碼在VB:
Public Delegate Sub xxxDelegate()
Sub xxxAnImplementation()
End Sub
Sub zzzDoIt(ByVal xxxImplementerName As String)
Dim theDelegate As xxxDelegate = CType(System.Delegate.CreateDelegate(GetType(xxxDelegate), Me, xxxImplementerName), xxxDelegate)
theDelegate.Invoke()
End Sub
Private Sub LoadFunctions()
Dim thisClass As Type = Type.GetType(Me.GetType.BaseType.FullName.ToString)
For Each method As MethodInfo In thisClass.GetMethods(System.Reflection.BindingFlags.DeclaredOnly)
If 1 = 1 OrElse method.Name.Substring(0, 3) = "Get" Then
Me.ddlCodeSamples.Items.Add(method.Name)
End If
Next
End Sub
+1和正確的,我會刪除我的 – ybo 2009-03-05 18:47:49