VBScript有条件的短路解决方法

VBScript有条件的短路解决方法

问题描述:

我有一个大型的经典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中确实存在一些超级秘密的方法吗?

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

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

+0

经典的VB没有真正的三元操作,只是IIf()函数(立即如果)。但即使这仍然是一个函数,所以在传递给函数之前,必须先计算_all_函数参数。 – 2008-09-12 18:43:15

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

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

我总是选择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 

如果你把它写成两个同轴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")) 

您可以只使用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 

我在测试这个我代码,它目前正在工作。虽然可能不适合每个人的情况。