动态调用方法

Calling Methods dynamically

我正在尝试动态调用方法,但遇到了问题。有人可以帮忙吗

我有以下vb代码

Module
    Sub Main
        if user-input = RP1 then
            createRP1()
        elseif user-input = RP2 then 
            createRP2()
        end if
    end sub

    sub createRP1()
        ...
    end sub

    sub createRP2()
        ,...
    end sub

End Module

CreateRP1/CreateRP2 方法没有任何参数。有一些报告。所以我不想为此编写所有这些 if 或 switch 条件。我想写一些简单的东西所以我试了这个

1 Dim type As Type = "["GetType"]"()
2 Dim method As MethodInfo = type.GetMethod("Create" + user-input)
3 If method IsNot Nothing Then
4     method.Invoke(Me, Nothing)
5 End If

1 号线和 4 号线不工作
第 4 行不工作,因为 "me" 不与模块一起使用。但是如何重写 1 呢?我在 Whosebug 网站的某处看到了这个

我认为最好的解决方案是通过设计 class 来创建一个 "Report" 对象。然后你就可以轻松地即时制作东西。

function (byRef user-input As String) As Report
    if not "s" & user-input = "s" 
        Dim user-report As Report = new Report(user-input)
    end if
end function

然后你的报告class

Private reportNumber As String
Private data As String
Public Sub New(byVal reportNumber As String) 
      Sub createRP(byRef repotNumber As String)
      // use report # here to select the correct data... 
      // so if it was sql.... 
      // "SELECT data FROM report_table where report_num =" & reportNumber
      end Sub
end Sub

你可以这样获取当前ModuleType

 Dim myType As Type = MethodBase.GetCurrentMethod().DeclaringType

因为它是一个 Module,所以所有方法本质上都是 Shared(例如静态、非实例方法),所以您可以只为 [=18] 传递 Nothing =] MethodInfo.Invoke 方法的参数:

 Dim methodName As String = "Create" & userInput
 Dim method As MethodInfo = myType.GetMethod(methodName)
 method.Invoke(Nothing, Nothing)

但是,除了使用反射之外,您可能还想考虑使用委托字典,这样它会在编译时更具确定性和类型检查。例如:

Dim methods As New Dictionary(Of String, Action)
methods.Add("RP1", AddressOf CreateRP1)
methods.Add("RP2", AddressOf CreateRP1)
' ...
methods(userInput).Invoke()