我试图动态地调用方法,但我有问题。有人能帮忙吗?
我有以下的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方法没有任何参数。有一些报告。因此,我不想写所有这些如果或切换条件的这一点。我想写一些简单的东西,所以我试了一下
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呢?我在StackOverflow网站的某个地方看到了这个
发布于 2015-10-21 18:38:12
您可以像这样获得当前Type
的Module
:
Dim myType As Type = MethodBase.GetCurrentMethod().DeclaringType
由于它是一个Module
,所以所有方法本质上都是Shared
(例如,静态的、非实例的方法),所以您只需为MethodInfo.Invoke
方法的obj
参数传递Nothing
:
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()
https://stackoverflow.com/questions/33265649
复制相似问题