質問

Perhaps I'm missing something, but it annoys me that VBScript seems to read all OR condtions. For example, I'd like to do something like this:

If (oFS.FileExists(sFileLoc) = False) Or (sNewText <> oFS.OpenTextFile(sFileLoc).ReadAll) Then

Now I get an error that the file doesn't exist because of the second condition. I was hoping that if the file doesn't exist VBScript would skip immediately to the result, and if it does, it checks the second condition.

Am I right and is this normal behavior?

役に立ちましたか?

解決

As M. Harris already said in 2003 and the docs for the logical operators (e.g. Or) state explicitly, VBScript does not short-circuit the evaluation of conditionals. You must use nested Ifs or a slightly fancy Select Case

他のヒント

You can use inline nested IF's to achieve short-circuiting in VBScript. For example, you could rewrite your statement like this:

If oFS.FileExists(sFileLoc) Then If sNewText = oFS.OpenTextFile(sFileLoc).ReadAll Then

But your Then condition must be specified on the same line as this statement. So if you need to perform multiple operations as a result of this condition, you must separate the statements with a colon (:), which is the single-line statement separator in VBScript.

If oFS.FileExists(sFileLoc) Then If sNewText = oFS.OpenTextFile(sFileLoc).ReadAll Then x = 1 : y = 2

You could also just move your logic into a Sub or Function and make a call instead:

If oFS.FileExists(sFileLoc) Then If sNewText = oFS.OpenTextFile(sFileLoc).ReadAll Then DoStuff

Note, too, that if you need to specify an Else clause, it must be specified on this line as well.

If oFS.FileExists(sFileLoc) Then If sNewText = oFS.OpenTextFile(sFileLoc).ReadAll Then x = 1 Else x = 2
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top