隐式转换与变量到文字不同

隐式转换与变量到文字不同

本文介绍了IF 语句中的 VBScript 隐式转换与变量到文字不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 VBScript(经典 ASP)中的 IF 语句中的隐式转换,我们目前遇到了一个问题,在处理变量或文字时,它不会以相同的方式进行隐式转换.有人可以向我解释这种行为吗,为什么 VBScript 会这样?

We are currently having an issue due to implicit conversion in an IF statement in VBScript (Classic ASP) that don't do implicit conversion the same way when dealing with a variable or a literal. Can someone explain this behavior to me, why do VBScript acts this way ?

这是我的意思的示例:

Const c_test = 3
Dim iId : iId = 3
Dim iTestStr : iTestStr = "3"

If iId = iTestStr Then
    Response.Write("Long variable = String variable : Equal")
Else
    Response.Write("Long variable = String variable : Not Equal")
End If

Response.Write("<br/>")

If c_test = iTestStr Then
    Response.Write("Long constant = String variable : Equal")
Else
    Response.Write("Long constant = String variable : Not Equal")
End If

Response.Write("<br/>")

If c_test = iId Then
    Response.Write("Long constant = Long variable : Equal")
Else
    Response.Write("Long constant = Long variable : Not Equal")
End If

Response.Write("<br/>")

If iId = "3" Then
    Response.Write("Long variable = String literal : Equal")
Else
    Response.Write("Long variable = String literal : Not Equal")
End If

Response.Write("<br/>")

If c_test = "3" Then
    Response.Write("Long constant = String literal : Equal")
Else
    Response.Write("Long constant = String literal : Not Equal")
End If

输出:

长变量 = 字符串变量:不相等

Long variable = String variable : Not Equal

长常量 = 字符串变量:不相等

Long constant = String variable : Not Equal

长常量 = 长变量:相等

Long constant = Long variable : Equal

长变量 = 字符串文字:相等

Long variable = String literal : Equal

长常量 = 字符串文字:相等

Long constant = String literal : Equal

这很令人困惑o_O

推荐答案

你(隐式地)声明你的变量 As Variant 所以你的 If 条件实际上测试了两个 Variant 并确定它们不相等.

You are (implicitly) declaring your variables As Variant so your If conditions actually test the equality of two Variants and determine that they are unequal.

然而,在最后一种情况下,您使用的是 String 常量(永远不能是 Variant,即使声明时没有类型)和 String文字.

In the last cases, however, you are using String constants (which can never be Variant, even if declared without a type) and String literals.

我的猜测是当你比较两个Variant时,VB首先判断它们是否具有相同的类型标签,如果没有,则解析为错误.

My guess is that when you compare two Variants, VB first determines whether they have the same type tag and if they don’t, resolves to False.

这篇关于IF 语句中的 VBScript 隐式转换与变量到文字不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 13:11