检查子或函数是否存在

时间:2016-03-10 14:30:11

标签: vbscript asp-classic

有没有办法检查子或函数是否存在?

sub mySub()
 'some code
end sub

类似于if exist(mySub)

1 个答案:

答案 0 :(得分:9)

更新

所以我知道有更好的方法可以做到这一点并使用GetRef()

Function Exist(procName)
    On Error Resume Next
    Dim proc: Set proc = GetRef(procName)
    Exist = (Not proc Is Nothing)
End Function

Function Hello()
    WScript.Echo "Hello Ran"
End Function

If Exist("test") Then  'Returns False (0)
    WScript.Echo "Test Exists"
Else
    WScript.Echo "Test Doesn't Exist"
End If

If Exist("Hello") Then  'Returns True (-1)
    WScript.Echo "Hello Exists"
Else
    WScript.Echo "Hello Doesn't Exist"
End If

输出

Test Doesn't Exist
Hello Exists

VBScript中没有内置任何功能,但您可以使用On Error Resume NextExecuteGlobal()构建内容。

Function Exist(procName)
    On Error Resume Next
    ExecuteGlobal "Call " & procName & "()"
    Exists = (Err.Number = 0)
End Function

Function Hello()
    WScript.Echo "Hello Ran"
End Function

If Exist("test") Then  'Returns False (0)
    WScript.Echo "Test Exists"
Else
    WScript.Echo "Test Doesn't Exist"
End If

If Exist("hello") Then  'Returns True (-1)
    WScript.Echo "Test Exists"
Else
    WScript.Echo "Test Doesn't Exist"
End If

输出

Test Doesn't Exist
Hello Ran
Test Doesn't Exist

使用这种方法的缺点是,如果它存在,它实际上会运行该程序。