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

tbo*_*one 2 .net vb.net delegates

我试图弄清楚是否可以通过名称实例化和调用委托,而不是显式.我认为下面的代码解释得相当好....我想接受一个函数名,然后基于它实例化委托.在示例中,我使用了一个选择案例,但我想要消除它,只需使用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
Run Code Online (Sandbox Code Playgroud)

谢谢基思,正是我想要的.(但在大多数情况下,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
Run Code Online (Sandbox Code Playgroud)

BFr*_*ree 5

我不会完全回答问题,因为我不确定你问的是否可能.但是,通过Reflection,可以调用给定方法名称的方法.IE:

    string methodName = "MyMethod";
    MethodInfo method = this.GetType().GetMethod(methodName);
    method.Invoke(this, null);
Run Code Online (Sandbox Code Playgroud)