这可能只是一厢情愿的想法...
有没有办法在调用ASP/VBScript函数之前检查它是否已定义?
这可能只是一厢情愿的想法...
有没有办法在调用ASP/VBScript函数之前检查它是否已定义?
这是我的解决方案,它基于同样的原理,但是“hacky-ness”相当自包含:
Function FunctionExists( func_name )
FunctionExists = False
On Error Resume Next
Dim f : Set f = GetRef(func_name)
If Err.number = 0 Then
FunctionExists = True
End If
On Error GoTo 0
End Function
这是一种有点巧妙的方法,它依赖于设置了“On Error Resume Next”,但你可以像这样做:
On Error Resume Next
Dim objRef1, objRef2
Set objRef1 = GetRef("DoStuff1")
If objRef1 Is Nothing Then
Call objRef1
Else
MsgBox "DoStuff1 is not defined!"
End If
Set objRef2 = GetRef("DoStuff2")
If objRef2 Is Nothing Then
MsgBox "DoStuff2 is not defined!"
Else
Call objRef2
End If
Sub DoStuff1
MsgBox "DoStuff1!"
End Sub
如果您尝试获取指向不存在的子程序或函数的指针(如DoStuff2),则调用GetRef将生成异常。然后,您可以检查是否按预期设置了引用。
Err.Clear
并基于提供的答案压缩了函数。
我还将函数重命名为更合适的名称,以反映它可以用于检查函数和子程序的存在。
Function ProcExists(ByVal ProcName)
On Error Resume Next
Set ProcName = GetRef(ProcName)
ProcExists = (Err.Number = 0)
Err.Clear
On Error GoTo 0
End Function
FunctionExists = (Err.Number = 0)
来设置布尔值。 - user692942