Vb.net 如何从字符串变量调用子例程?
使用VB.Net 4和VS2012 我有一个模块,其中包含一些逻辑,如下所示:Vb.net 如何从字符串变量调用子例程?,vb.net,string,converter,subroutine,Vb.net,String,Converter,Subroutine,使用VB.Net 4和VS2012 我有一个模块,其中包含一些逻辑,如下所示: Module Mod1 If x = 1 then Mod2("Mod3","save_it") else Mod2("Mod4","edit_it") end if End Module Module Mod2(which_mod, which_action) ' call the correct subroutine which_mod.
Module Mod1
If x = 1 then
Mod2("Mod3","save_it")
else
Mod2("Mod4","edit_it")
end if
End Module
Module Mod2(which_mod, which_action)
' call the correct subroutine
which_mod.which_action()
End Module
如何使用字符串从不同模块调用正确的子例程?查看System.Reflection命名空间,它包含一个名为MethodInfo的类 您可以使用方法名称获取给定对象的MethodInfo,然后调用它:
Dim method As MethodInfo = obj.GetType().GetMethod(methodName, BindingFlags.Instance Or BindingFlags.Public)
method.Invoke()
有一个函数CallByName
正是这样做的
该函数接受4个参数:
- 对象/类
- 函数/程序名
- calltype(calltype.method、calltype.Get、calltype.Set)
- (可选):参数(以arrayformat格式)
Dim MyInstance As Object = Activator.CreateInstance(Type.GetType(which_mod))
因此,对于您的代码:
Imports Microsoft.VisualBasic.CallType
Imports System.Reflection
Class Mod1
If x = 1 then
Mod2("Mod3","save_it")
else
Mod2("Mod4","edit_it")
end if
End Class
Module Mod2(which_mod, which_action)
' call the correct subroutine
Dim MyInstance As Object = Activator.CreateInstance(Type.GetType(which_mod))
CallByName(MyInstance , which_action, CallType.Method)
End Module
那个有效的语法是什么语言?它肯定不是VB.NET。你不能向模块主体添加逻辑,你必须使用一个方法。你为什么要这样做?你的潜在需求是什么?@Enigmativity我同意。这看起来确实像是一个问题。语法是为了简洁而缩写的,只是为了演示这个问题。不全面,非常接近。
which_mod
变量是一个对象
而不是一个字符串
。这就是对象字符串字典的作用。要从字符串中查找对象,需要进行某种类型的查找。@Enigmativity我使用了系统.Reflection
库,这在@trucket\u jim的答案中也提到了获取对象。不能使用反射来获取对象引用-首先需要对象引用才能使用反射。也就是说,除非您使用反射来实际创建实例,否则这看起来更像依赖项注入。