【问题标题】:How to test boolean expressions in VBScript?如何在 VBScript 中测试布尔表达式?
【发布时间】:2010-12-29 13:05:06
【问题描述】:

我正在尝试将代码从 https://stackoverflow.com/questions/4554014/how-to-examine-and-manipulate-iis-metadata-in-c 转换为 VBVcript。

我的问题在于这段代码:

Function LocateVirtualDirectory(ByVal siteName, ByVal vdirName)
    On Error Resume Next
    Dim site
    For Each site in w3svc
        If (site.KeyType = "IIsWebServer") And (site.ServerComment = siteName) Then
            Set LocateVirtualDirectory = GetObject(site.Path & "/ROOT/" & vdirName)
            Exit Function
        End If
    Next
End Function

如果site.ServerCommentEmpty,则整个布尔表达式接收值Empty,它不是 False,因此输入 then 语句。

编写该表达式的正确方法是什么?越短越好。

谢谢。

【问题讨论】:

    标签: vbscript boolean boolean-expression


    【解决方案1】:

    我会简单地嵌套If 语句,并插入一个额外的检查来防止ServerCommentEmpty 的情况。我还将site.ServerComment 的值提取到临时变量comment 中,这样您就不会访问该属性两次。

    例如:

    Function LocateVirtualDirectory(ByVal siteName, ByVal vdirName)
        On Error Resume Next
        Dim site
        Dim comment
        For Each site in w3svc
            If site.KeyType = "IIsWebServer" Then
                comment = site.ServerComment
                If (comment <> Empty) And (comment = siteName) Then
                    Set LocateVirtualDirectory = GetObject(site.Path & "/ROOT/" & vdirName)
                    Exit Function
                End If
            End If
        Next
    End Function
    

    嵌套If 语句的另一个好处是使评估短路。 VBScript(和 VB 6)不会短路条件求值——And 运算符作为一个逻辑运算符工作,要求条件的两边都经过测试才能确定结果。因为如果KeyType 不匹配,则没有理由检查ServerComment,因此通过短路表达式可以获得一点性能。在 VBScript 中实现这一点的唯一方法是嵌套(没有 AndAlso)。

    我还应该指出,如果值= True,测试绝对没有意义。您可以简单地将(site.ServerComment = siteName) = True 重写为site.ServerComment = siteName,并获得完全相同的结果。我至少花了几分钟才弄清楚你的原始代码做了什么,因为那是一种不自然的编写条件的方式。

    【讨论】:

    • 我推荐If Not IsEmpty(site.ServerComment) And ...,但无论如何……将Empty 变量与字符串进行比较会得到False,而不是Empty。将EmptyEmpty 进行比较也会得出False
    • 奇怪,我试图使用 IsEmpty 但它不起作用。我想我混淆了一些东西。
    • 是的,我的想法和 Tomalak 一样。我很难想象你所描述的行为,但变体一直是一个主要的痛苦。当我写答案时,我在 Mac 上,没有 VBScript 方便用于测试目的。不管怎样,我很高兴看到你现在走在正确的轨道上。
    猜你喜欢
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    • 2010-09-21
    • 2014-03-23
    • 1970-01-01
    • 2022-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多