VBScript中的整数和字符串比较冲突 [英] Integer and String comparison conflict in VBScript

查看:124
本文介绍了VBScript中的整数和字符串比较冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的VBScript代码试图在HP-UFT中运行时感到困惑,因为第一条语句打印的是True而不是False(这似乎不合逻辑),而第二条语句打印的是False(这似乎合乎逻辑) )

代码:

print 40 = "40"

a = 40
b = "40"
print a = b

输出:

True
False

解决方案

这完全符合逻辑(咳嗽),VBScript中只有一种数据类型,即Variant.但是,VBScript可以处理Variant数据类型的许多不同子类型.

比较时

40 = "40"

VBScript正在将String子类型隐式转换为Integer子类型,并比较与执行以下显式转换相同的结果;

40 = CInt("40")

如果已经定义了变体,但是VBScript仅在执行上下文适合的情况下才尝试隐式转换它们(适合时有点朦胧,在某些情况下是简单的错误-请参见 A:IF语句中的VBScript隐式转换(从变量到文字)有所不同吗?

  • MSDN博客-刻苦打字会绊倒你(Eric Lippert)
  • The below VBScript code while trying to run in HP-UFT confused me because the first statement prints True instead of False (which does not seem logical), while the second one prints False (which seems logical)

    Code:

    print 40 = "40"
    
    a = 40
    b = "40"
    print a = b
    

    Output:

    True
    False
    

    解决方案

    It's perfectly logical (cough), there is only one data type in VBScript and that is Variant. However VBScript can handle many different sub types of the Variant data type.

    When you compare

    40 = "40"
    

    VBScript is implicitly converting the String sub type to an Integer sub type and comparing the result which is the same as performing the following explicit conversion;

    40 = CInt("40")
    

    If you already have your variants defined however VBScript only attempts to implicitly convert them if the execution context fits (when it fits is a bit hazy and in some cases a straight up bug - See Ref).

    To avoid this use explicit conversions when necessary.

    a = CInt(b)
    


    Useful Links

    这篇关于VBScript中的整数和字符串比较冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆