質問

私には、保守しなければならない大規模なクラシック ASP アプリがありますが、ショートサーキット評価機能の欠如によって何度も妨げられています。たとえば、VBScript では次のような問題を回避できません。

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

...Rs("myField") が null の場合、null と 0 を比較する 2 番目の条件でエラーが発生するためです。したがって、通常は代わりにこれを行うことになります。

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

VB でロジックを短絡するには、常に Select Case ステートメントを使用していました。何かのようなもの..

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

インラインで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"))

あったらよかったのに、友よ -- TernaryOp が唯一の希望です。

はい、それは最良の解決策ではありませんが、私たちが使用しているのは次のようなものです

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

2 つの選択肢が思い浮かびます。

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、"" などをキャッチします。

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

コードでこれをテストしましたが、現在動作しています。ただし、すべての人の状況に適しているわけではないかもしれません。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top