【问题标题】:Is there any way to check to see if a VBScript function is defined?有什么方法可以检查是否定义了 VBScript 函数?
【发布时间】:2009-05-28 15:10:29
【问题描述】:

这大概只是一厢情愿……

有什么方法可以在调用之前检查是否定义了 ASP/VBScript 函数?

【问题讨论】:

    标签: function asp-classic vbscript defined


    【解决方案1】:

    这是我的解决方案,其工作原理相同,但 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 
    

    【讨论】:

    • 是的 - 这就是我最终用它做的事情。 :-)
    • 您可以将其简化为FunctionExists = (Err.Number = 0) 以设置Boolean
    • @Lankymart,不一样。不知道为什么不。
    • 可以简化为:If Err.number = 0 Then FunctionExists = True
    【解决方案2】:

    这是一种有点老套的方法,因为它依赖于设置“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
    

    如果您尝试获取指针的子函数或函数不存在,则对 GetRef 的调用将生成异常(如 DoStuff2 的情况)。然后,您可以检查引用是否按预期设置。

    【讨论】:

    • 否则你会在尝试调用函数后检查 Err.Number。但是你调用的函数可能被定义,被调用,但是是错误的来源,我猜这不是你想要的。
    【解决方案3】:

    提供的答案是正确的,我只是做了一个简单的修改,添加了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
    

    【讨论】:

      猜你喜欢
      • 2011-07-13
      • 1970-01-01
      • 2015-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      相关资源
      最近更新 更多