我有以下VB脚本,如何用case语法写这个VB脚本?为了在适当的地方执行专业写作if then…。雅艾尔
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists("C:\file1 ")) Then
Verification=ok
Else
WScript.Echo("file1")
Wscript.Quit(100)
End If
If (fso.FileExists("C:\file2 ")) Then
Verification=ok
Else
WScript.Echo("file2")
Wscript.Quit(100)
End If
If (fso.FileExists("C:\file3 ")) Then
Verification=ok
Else
WScript.Echo("file3")
Wscript.Quit(100)
End If。。。。
发布于 2010-06-15 00:34:20
您不能使用select/case来处理这种类型的事情,但是有其他方法可以压缩或简化代码。
首先,颠倒测试条件:
If Not (fso.FileExists("C:\file1 ")) Then
WScript.Echo("file1")
Wscript.Quit(100)
End If 这就避免了在if/then之后需要“什么都不做”命令。
接下来,您可以将其封装在函数和子例程中,以减少重复的大量代码:
function TestFile(sFileName)
TestFile = fso.FileExists(sFileName)
end function
sub ErrorExit(sMessage, nCode)
WScript.Echo sMessage
WScript.Quit nCode
end sub那么你的一系列测试就变成了:
if not TestFile("c:\file1") then
ErrorExit "file1 not found", 100
elseif not TestFile("c:\file2") then
ErrorExit "file2 not found", 100
elseif not TestFile("c:\file3") then
ErrorExit "file3 not found", 100
end if发布于 2010-06-13 22:32:16
VB (或vbs)中的with子句或其他语言中的switch子句也有其他选择,但是这些都是用于单个给定的条件/var,然后检查它们的值,但因为您不必检查单个内容,例如多个文件名C:\file1,C:\file2等,所以在这种情况下使用它们不适用。
作为另一种选择,您可以使用循环,因为您的代码中的文件名号似乎是一致的:
For i 1 To 3
If (fso.FileExists("C:\file" & i)) Then
Verification = ok
Else
WScript.Echo("file" & i)
Wscript.Quit(100)
End If
Next总而言之,上面的代码是您的代码的速记。
发布于 2010-06-13 22:31:16
虽然这可能需要更多的代码行,但您可以实现一个简单的有限状态机来完成此任务。然后,您将不再使用if/then构造,而是使用某种类型的switch语句,以及您可能处于的枚举“状态”集。
这里详细介绍了FSM http://en.wikipedia.org/wiki/Finite-state_machine,它们很容易使用枚举和switch语句来实现。
我刚刚拿到了Google的这个,这是一个简单的FSM实现:
#include <stdio.h>
main()
{
int c;
START:
switch(c = getchar()){
case 'f' : goto F;
case 'b' : goto B;
case EOF : goto FAIL;
default: goto START; }
F:
switch(c = getchar()){
case 'o' : goto FO;
case EOF : goto FAIL;
default : goto START;}
FO:
switch(c = getchar()){
case 'o' : goto SUCCESS;
case EOF : goto FAIL;
default : goto START;}
B:
switch(c = getchar()){
case 'a' : goto BA;
case EOF : goto FAIL;
default : goto START;}
BA:
switch(c = getchar()){
case 'r' : goto SUCCESS;
case EOF : goto FAIL;
default : goto START;}
FAIL:
printf("Does not match.\n");
return;
SUCCESS:
printf("Matches.\n");
return;
}https://stackoverflow.com/questions/3032545
复制相似问题