2008-09-12 12 views
14

我有一個大型的經典ASP應用程序,我不得不維護,並且我一再發現自己由於缺乏短路評估能力而受挫。例如,VBScript中不會讓你逃脫:VBScript有條件的短路解決方法

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

...因爲如果盧比(「MyField的」)爲空,你在第二個狀態的錯誤,比較空爲0。所以我我通常最終會這樣做:

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

if myField <> 0 then 
... 

顯然,冗長是相當可怕的。回顧一下這個龐大的代碼庫,我發現的最好的解決方法是使用原始程序員寫的名爲TernaryOp的函數,它基本上在三元運算符類功能中移植,但我仍然使用臨時變量卡住在更全面的功能語言中是必要的。有沒有更好的辦法? VBScript中確實存在一些超級祕密的方法嗎?

回答

8

也許不是最好的方法,但它肯定有效......另外,如果你在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 
9

嵌套的IF(僅略少詳細):

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

會,有,我的朋友 - TernaryOp是你唯一的希望。

+0

經典的VB沒有真正的三元操作,只是IIf()函數(立即如果)。但即使這仍然是一個函數,所以在傳遞給函數之前,必須先計算_all_函數參數。 – 2008-09-12 18:43:15

1

啊這不是最好的解決方案,但我們用的是這樣的

function ReplaceNull(s) 
    if IsNull(s) or s = "" then 
     ReplaceNull = "&nbsp;" 
    else 
     ReplaceNull = s 
    end if 
end function 
4

我總是選擇Case語句短路邏輯VB。就像..

Select Case True 

Case isNull(Rs("myField")) 

    myField = 0 

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

    myField = Rs("myField") 

Case Else 

    myField = -1   

End Select 

我的語法可能已關閉,已經有一段時間了。如果第一個案例彈出,則其他所有內容都將被忽略。

0

兩個選項浮現在腦海中:

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 
3

或者我得到了錯誤的結論。你的意思是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 
2

如果你把它寫成兩個同軸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")) 
0

您可以只使用Else抓空 「」 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 

我在測試這個我代碼,它目前正在工作。雖然可能不適合每個人的情況。