VBScript有条件的短路解决方法

时间:2020-03-05 18:52:24  来源:igfitidea点击:

我有一个必须维护的大型经典ASP应用程序,但我一再发现自己因缺乏短路评估功能而受挫。例如,VBScript不会让我们摆脱:

if not isNull(Rs("myField")) and Rs("myField") <> 0 then
...

...因为如果Rs(" myField")为null,则在第二种情况下会出现错误,将null与0进行比较。因此,我通常会改为这样做:

dim myField
if isNull(Rs("myField")) then 
    myField = 0
else
    myField = Rs("myField")
end if

if myField <> 0 then
...

显然,冗长是非常令人震惊的。围绕这个庞大的代码库,我发现最好的解决方法是使用原始程序员编写的名为TernaryOp的函数,该函数基本上嫁接到类似三元运算符的功能中,但是我仍然停留在使用临时变量而不会是功能更全面的语言所必需的。有没有更好的办法? VBScript中确实存在某种超级秘密的短路方式吗?

解决方案

回答

嵌套的IF(仅略为冗长):

if not isNull(Rs("myField")) Then
   if Rs("myField") <> 0 then

回答

会有,我的朋友-TernaryOp是我们唯一的希望。

回答

也许不是最好的方法,但是它肯定可以工作...此外,如果我们使用的是vb6或者.net,也可以使用将不同的方法转换为正确的类型。

if cint( getVal( rs("blah"), "" ) )<> 0 then
  'do something
end if

function getVal( v, replacementVal )
  if v is nothing then
    getVal = replacementVal
  else
    getVal = v
  end if
end function

回答

是的,这不是最好的解决方案,但是我们使用的是这样的东西

function ReplaceNull(s)
    if IsNull(s) or s = "" then
        ReplaceNull = " "
    else
        ReplaceNull = s
    end if
end function

回答

我总是使用Select Case语句来短路VB中的逻辑。就像是..

Select Case True

Case isNull(Rs("myField"))

    myField = 0

Case (Rs("myField") <> 0)

    myField = Rs("myField")

Case Else

    myField = -1        

End Select

我的语法可能关闭了一段时间。如果出现第一种情况,其他所有内容都将被忽略。

回答

我想到两个选择:

1)使用len()或者lenb()来发现变量中是否有任何数据:

if not lenb(rs("myField"))=0 then...

2)使用返回布尔值的函数:

if not isNothing(rs("myField")) then...

其中" isNothing()"是一个类似这样的函数:

function isNothing(vInput)
    isNothing = false : vInput = trim(vInput)
    if vartype(vInput)=0 or isEmpty(vInput) or isNull(vInput) or lenb(vInput)=0 then isNothing = true : end if 
end function

回答

也许我的答案错了。我们是说VB中的" iIf()"之类的意思吗?这对我有用:

myField = returnIf(isNothing(rs("myField")), 0, rs("myField"))

其中," returnIf()"是类似的函数:

function returnIf(uExpression, uTrue, uFalse)
    if (uExpression = true) then returnIf = uTrue else returnIf = uFalse : end if
end function