可能通过名称实例化和调用委托?

问题描述:

我想知道是否有可能通过名称而不是明确地实例化和调用委托。我认为下面的代码很好地解释了它....我想接受一个函数名称,然后基于此实例化委托。在这个例子中,我使用了一个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 

如果你有一个委托的方法,你也可以这样做:

public delegate void MethodDelegate(...) ... 

//create the delegate we expect 
(MethodDelegate) Delegate.CreateDelegate(
    typeof(MethodDelegate), this, "methodName", true); 

C#,我知道,但类似将在VB中工作。

通常情况下,我会与@ BFree的答案一起去,但是在使用事件驱动反射的时候这个效果很好 - 我认为如果调用结果委托很多次,这会稍微快一点。

为什么不使用哈希表来代替SELECT语句的?

我不会完全回答问题,因为我不确定你问的是否可能。通过Reflection,尽管可能是通过调用方法名称来调用方法。 IE:

string methodName = "MyMethod"; 
    MethodInfo method = this.GetType().GetMethod(methodName); 
    method.Invoke(this, null); 
+0

+1和正确的,我会删除我的 – ybo 2009-03-05 18:47:49

BFree's answer工程;

我的回答只是一个建议;

为什么不把方法的地址传递给InvokeMethod,而不是将字符串中的方法名传给它?

Module Module1 
Sub Main() 
    InvokeMethod(AddressOf myDelegate_Implementation1) 
    InvokeMethod(AddressOf myDelegate_Implementation2) 
End Sub 

Public Delegate Sub myDelegate() 

Private Sub myDelegate_Implementation1() 
    Console.WriteLine("myDelegate_Implementation1") 
End Sub 
Private Sub myDelegate_Implementation2() 
    Console.WriteLine("myDelegate_Implementation2") 
End Sub 

Public Sub InvokeMethod(ByVal func As myDelegate) 
    func() 
End Sub 
End Module