题
我有一个大的经典ASP应用程序,我得以维持,并且我多次发现自己挫败了由于缺乏短路评价能力。E.g., VBScript不会让你得逞:
if not isNull(Rs("myField")) and Rs("myField") <> 0 then
...
...因为如果Rs("myField")是空的,你得到一个错误,在第二个条件,比较null为0。所以我通常会最终这样做,而不是:
dim myField
if isNull(Rs("myField")) then
myField = 0
else
myField = Rs("myField")
end if
if myField <> 0 then
...
显然,verboseness是相当令人震惊。看看这个大码的基地,最好的解决办法,我发现是使用一种功能的原始程序员写信,称为TernaryOp,基本上移植在三操作员喜欢的功能,但是,我仍然坚持使用临时变量,就没有必要在一个多功能齐全的语言。是否有一个更好的办法?一些超级秘密的方式,短路确实存在VBScript?
解决方案
也许不是最好的方式,但它肯定的工作...还有,如果你是在维生素b6。净的,你可以有不同的方法,转换为适当的类型。
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
其他提示
嵌套IFs(只有略少详细):
if not isNull(Rs("myField")) Then
if Rs("myField") <> 0 then
我总是选择的情况下发言,以短路逻辑VB。喜欢的东西..
Select Case True
Case isNull(Rs("myField"))
myField = 0
Case (Rs("myField") <> 0)
myField = Rs("myField")
Case Else
myField = -1
End Select
我的语法可以断,已经有一段时间。如果第一种情况下持久性有机污染物,其他一切都被忽略。
或许我得到了错误的结束这个问题。你的意思是喜欢的东西 iIf()
在VB?这个工作对我来说:
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
如果你写的这两个内联 IF
发言,就可以实现的短路:
if not isNull(Rs("myField")) then if Rs("myField") <> 0 then ...
但你的 then
行动必须出现在同一行为。如果你需要多个发言之后 then
, 你可以单独与他们的 :
或移动你的代码有一个子程序,你可以打电话。例如:
if not isNull(Rs("myField")) then if Rs("myField") <> 0 then x = 1 : y = 2
或
if not isNull(Rs("myField")) then if Rs("myField") <> 0 then DoSomething(Rs("myField"))
会有的,我的朋友-TernaryOp是你唯一的希望。
是啊这是不是最好的解决办法,但我们用什么是像这样的东西
function ReplaceNull(s)
if IsNull(s) or s = "" then
ReplaceNull = " "
else
ReplaceNull = s
end if
end function
两种选择来考虑:
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
你可能能够就使用 Else
赶null,""s,等等。
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
我已经测试了这个在我的代码,它的目前工作。可能不适用于每个人的情况。