动态调用方法

时间:2015-10-21 17:29:24

标签: asp.net vb.net module gettype

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

我有以下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或切换条件。我想写一些简单的东西,所以我尝试了这个

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行无效,因为“我”不适用于模块。但如何重写1?我在StackOverflow网站的某个地方看到了这个

2 个答案:

答案 0 :(得分:2)

您可以像这样获取当前Type的{​​{1}}:

Module

由于它是 Dim myType As Type = MethodBase.GetCurrentMethod().DeclaringType ,所有方法基本上都是Module(例如静态,非实例方法),因此您可以为Shared传递Nothing obj方法的参数:

MethodInfo.Invoke

但是,您可能还需要考虑使用委托字典,以便在编译时更加确定并进行类型检查,而不是使用反射。例如:

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

答案 1 :(得分:0)

我认为最好的解决方案是通过设计一个类来创建一个“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

然后是您的报告类

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
相关问题