如何在 VBScript 中测试布尔表达式?
我正在尝试从 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.ServerComment
为 Empty
,则整个布尔表达式接收值 Empty
,该值不是 False 并且因此输入了 then 语句。
该表达式的正确写法是什么?越短越好。
谢谢。
I am trying to convert the code from https://stackoverflow.com/questions/4554014/how-to-examine-and-manipulate-iis-metadata-in-c to VBVcript.
My problem is with this code:
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
If site.ServerComment
is Empty
, then the whole boolean expression receives the value Empty
, which is not False and hence the then-statement is entered.
What is the right way to write that expression? The shorter the better.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我只需嵌套
If
语句,并插入一个额外的检查来防止ServerComment
为Empty
的情况。我还将site.ServerComment
的值提取到临时变量comment
中,这样您就不会两次访问该属性。例如:
嵌套
If
语句的另一个好处是可以缩短计算过程。 VBScript(和 VB 6)不会短路条件计算 -And
运算符作为逻辑运算符工作,要求测试条件的两侧才能确定结果。因为如果KeyType
不匹配,则没有理由检查ServerComment
,因此通过短路表达式,您将获得一些性能提升。在 VBScript 中实现这一点的唯一方法是嵌套(没有AndAlso
)。我还应该指出,测试值是否
= True
绝对没有意义。您可以简单地将(site.ServerComment = siteName) = True
重写为site.ServerComment = siteName
,并获得完全相同的结果。我至少花了几分钟才弄清楚你的原始代码到底做了什么,因为这是一种不自然的编写条件的方式。I would simply nest the
If
statements, and insert an additional check to guard against the condition whereServerComment
isEmpty
. I've also extracted the value ofsite.ServerComment
into the temporary variablecomment
so that you won't be accessing the property twice.For example:
Another benefit of nesting the
If
statements is to short-circuit the evaluation. VBScript (and VB 6) don't short-circuit conditional evaluations—theAnd
operator works as a logical one, requiring that both sides of the conditional are tested in order for a result to be determined. Because there's no reason to check theServerComment
if theKeyType
doesn't match, you'll gain a little in performance by short-circuiting the expression. The only way to achieve that in VBScript is nesting (there is noAndAlso
).I should also point out that there is absolutely no point to testing if a value
= True
. You can simply rewrite(site.ServerComment = siteName) = True
assite.ServerComment = siteName
, and achieve exactly the same result. It took me at least several minutes to figure out what your original code even did because that's such an unnatural way of writing conditionals.