ElseIf 与 Else If

ElseIf vs Else If

多年来,我一直在使用 Else If 在 VBScript 中编写代码...

If a = b Then
    ...
Else If a = c Then
    ...
End If

这似乎符合要求。我也在网上看到很多网站都使用 Else If,除了 MSDN 使用 ElseIf.

ElseIfElse If 有区别吗?

片段

这是我之前编写的代码,在 Classic ASP:

中运行良好
If IsDate(wD) Then
    wS = wD
Else If wD&"" <> FormatDisplayDate(wS) Then
    wS = WeekStart(Date())
    wD = FormatDisplayDate(wS)
End If

这是一段旧代码的片段,由其他人编写...

if opip = "IP" then
    opip = "In Patient"
Else If opip = "OP" then
    opip = "Out Patient"
End If

None 其中 运行 通过编译器,但是,它们都是解释的。

忽略那个垃圾 - 我搞砸了 IDE 中的搜索和替换。

Else If 将嵌套的 If 放入第一个 If 语句的 Else 分支中,而 ElseIf 是初始 [=13= 的一部分]声明。

基本上它是两个双向条件(一个嵌套在另一个)

If condition Then
  ...
Else
  If condition Then
    ...
  Else
    ...
  End If
End If

vs 一个 n-way 条件

If condition Then
  ...
ElseIf condition Then
  ...
Else
  ...
End If

并且,正如 指出的那样,前者应该在没有关闭嵌套 End If.

的情况下引发错误

该示例代码未编译并产生编译错误

Microsoft VBScript compilation error: Expected 'End'

如我所料(如@ekkehard-horner ).

我从来不知道 ElseIf 还有其他工作方式 detailed in MSDN。我唯一能想到的就是你把它写成嵌套的 If 语句。

If a = b Then
    ...
Else If a = c Then
    ...
End If
End If

虽然看起来很丑但是和写的一样

If a = b Then
    ...
Else
    If a = c Then
        ...
    End If
End If

这种方法的问题是您最终会在嵌套的 If 语句中遇到未处理的条件。例如,如果 a = d 会怎样?

您需要确保您的嵌套 If 捕获了 ElseIf 语句不需要的额外条件。

If a = b Then
    ...
Else
    If a = c Then
        ...
    Else
        ...
    End If
End If

ElseIf 方法是;

If a = b Then
    ...
ElseIf a = c Then
    ...
Else
    ...
End If

by @eric-lippert (VBScript 编译器背后的程序员之一) 在评论的海洋中......非常值得一读。我当然学到了一些东西。