【问题标题】:Check if a sub or a function exist检查子或函数是否存在
【发布时间】:2016-03-10 23:17:35
【问题描述】:

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

sub mySub()
 'some code
end sub

类似if exist(mySub)

【问题讨论】:

  • 如果这是因为您要链接多个源文件,您可以为每个源文件添加一个const x = true,然后稍后检查x

标签: vbscript asp-classic


【解决方案1】:

更新:

所以我知道有一个更好的方法可以做到这一点,它使用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

输出

测试不存在 你好存在

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

输出

测试不存在 你好冉 测试不存在

这种方法的缺点是它实际上会运行该过程(如果存在)。

【讨论】:

  • 为什么要ExecuteGlobal?我正在使用你的函数,只使用 Execute 并且像一个魅力一样工作!
  • @Vixed ExecuteGlobal 在全局范围内执行,而 Execute 取决于范围,它适用于简单的命令,但我发现更复杂的命令 ExecuteGlobal 效果更好。
  • @Vixed 有一种更简洁的方法,那就是使用GetRef() 我知道存在一个(以前使用过),只是不记得该命令。查看更新的答案。
  • 我已经构建了这个函数Function runIfExists(procName) On Error Resume Next Execute ("Call "&procName) End Function 但我得到一个错误错误'ASP 0115',可捕获错误(C0000005)你有什么建议给我吗?!
  • @Vixed 什么都没有想到,最好问另一个问题并添加您构建的功能。与此同时,这可能会有所帮助,Classic ASP : C0000005 Error on execution。我实际上以为您已经对其进行了测试并且有效,您是否按照上述答案中的代码进行操作,有什么不同吗?例如,你怎么称呼它?
猜你喜欢
  • 1970-01-01
  • 2018-05-23
  • 2012-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-22
  • 2011-10-23
  • 2010-11-10
相关资源
最近更新 更多