首页 / 知识

关于ASP Classic:VBScript有条件的短路解决方法

2023-04-15 03:55:00

关于ASP Classic:VBScript有条件的短路解决方法

VBScript conditional short-circuiting workaround

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

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

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

1
2
3
4
5
6
7
8
9
dim myField
if isNull(Rs("myField")) then
    myField = 0
else
    myField = Rs("myField")
end if

if myField <> 0 then
...

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


嵌套IF(仅略微冗长):

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

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

1
2
3
4
5
6
7
8
9
10
11
12
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


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Select Case True

Case isNull(Rs("myField"))

    myField = 0

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

    myField = Rs("myField")

Case Else

    myField = -1        

End Select

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


如果将其编写为两个内联IF语句,则可以实现短路:

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

但是您的then操作也必须出现在同一行上。如果在then之后需要多个语句,则可以用:将它们分开,或者将代码移到可以调用的子例程中。例如:

1
if not isNull(Rs("myField")) then if Rs("myField") <> 0 then x = 1 : y = 2

要么

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

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

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

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

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

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

1
2
3
4
5
6
7
function ReplaceNull(s)
    if IsNull(s) or s ="" then
        ReplaceNull =""
    else
        ReplaceNull = s
    end if
end function


我的朋友-TernaryOp是否会是您唯一的希望。


您也许可以只使用Else来捕获空值," s"等。

1
2
3
4
5
6
7
8
If UCase(Rs("myField")) ="THING" then
  'Do Things
elseif UCase(Rs("myField")) ="STUFF" then
  'Do Other Stuff
else
  'Invalid data, such as a NULL,"", etc.
  'Throw an error, do nothing, or default action
End If

我已经在我的代码中对其进行了测试,并且目前正在运行。但是可能不适合每个人的情况。


我想到两个选择:

1)使用len()lenb()查找变量中是否有任何数据:

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

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

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

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

1
2
3
4
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

解决方法应用程序评估维护

最新内容

相关内容

猜你喜欢