Asp-Classic

VBScript 條件短路解決方法

  • July 13, 2016

我有一個必須維護的大型經典 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中確實存在短路的一些超級秘密方式?

也許不是最好的方法,但它確實有效……此外,如果您使用的是 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

嵌套的 IF(只是稍微不那麼冗長):

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

引用自:https://stackoverflow.com/questions/59599