如何调用函数库中的函数(带参数),从变量中获取函数名? [英] How to call a function (with parameters) which is in function library, taking the function name from a variable?
问题描述
我正在尝试使用 getref 从与测试关联的函数库中调用函数.我的代码 -
I'm trying to use getref to call a function from the function library associated with the test. My code -
在行动1
str = "sample"
msg = "hi"
x = GetRef("Function_"&str)(msg)
msgbox x
在函数库中,
Function Function_sample(strMsg)
Function_sample = strMsg
End Function
我收到错误 -
无效的过程调用或参数."
"Invalid procedure call or argument."
但是如果将函数放在同一个动作中,它就可以正常工作.如何调用函数库中的函数(带参数),从变量中取函数名?
But it works fine if the function is placed in the same action. How to call a function (with parameters) which is in function library, taking the function name from a variable?
推荐答案
简约的工作示例:
Lib.vbs:
Option Explicit
Function Twice(n)
Twice = n + n
End Function
Main.vbs:
Option Explicit
Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")
ExecuteGlobal goFS.OpenTextFile(".\lib.vbs").ReadAll()
Dim fpTwice : Set fpTwice = GetRef("Twice")
WScript.Echo fpTwice(42)
输出:
cscript main.vbs
84
错误消息...运行时错误:无效的过程调用或参数:'GetRef'"表明(导入)函数库是罪魁祸首.
The error message "... runtime error: Invalid procedure call or argument: 'GetRef'" indicates that the (importing of the) function library is to blame.
更新:
我认为可以假设 VBScript 引擎保留一个表,将子/函数/方法名称与可调用代码相关联,以便能够进行文字/直接调用:
I think that it is plausible to assume that the VBScript engine keeps a table associating sub/function/method names with callable code to be able to do literal/direct calls:
n = Twice(11)
并且 GetRef("Twice") 访问这个表.因此,当文字调用成功时,我永远不会期望间接/函数指针"调用或 GetRef() 失败.
and that GetRef("Twice") accesses this table. So I would never expect an indirect/'function pointer' call or a GetRef() to fail when the literal invocation succeeds.
但根据 这个和那个,至少有四种方法可以将库/模块导入"到 QTP,因为我不使用 QTP,我不能排除这些方法中的一些(甚至全部)可以一些愚蠢的事情会导致您描述的错误行为.
But according to this and that, there are at least four ways to 'import' libraries/modules into QTP, and as I don't use QTP I can't rule out, that some (or even all) of these methods do something silly to cause the mis-behaviour you describe.
这篇关于如何调用函数库中的函数(带参数),从变量中获取函数名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!