string VBScript 的 + 和 & 运算符有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1208894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:29:51  来源:igfitidea点击:

What is the difference between VBScript's + and & operator?

stringvbscriptstring-concatenation

提问by Jeremy Cron

On every site that talks about VBScript, the '&' operator is listed as the string concatenation operator. However, in some code that I have recently inherited, I see the '+' operator being used and I am not seeing any errors as a result of this. Is this an accepted alternative?

在每个讨论 VBScript 的站点上,' &' 运算符都被列为字符串连接运算符。但是,在我最近继承的一些代码中,我看到使用了 ' +' 运算符,并且我没有看到任何由此产生的错误。这是可接受的替代方案吗?

回答by Helen

The &operator does string concatenation, that is, forces operands to be converted to strings (like calling CStron them first). +, in its turn, forces addition if one of the expressions is numeric. For example:

&运营商做字符串连接,那就是势力的操作数转换为字符串(如调用CStr它们在前)。+,反过来,如果表达式之一是数字,则强制加法。例如:

1 & 2

gives you 12, whereas

给你12,而

1 + 2
"1" + 2
1 + "2"

give you 3.

给你3

So, it is recommended to use &for string concatenation since it eliminates ambiguity.

因此,建议&用于字符串连接,因为它消除了歧义。

回答by Robert Harvey

The + operator is overloaded, whereas the & operator is not. The & operator only does string concatenation. In some circles the & operator is used as a best practice because it is unambiguous, and therefore cannot have any unintended effects as a result of the overloading.

+ 运算符被重载,而 & 运算符不是。& 运算符只进行字符串连接。在某些圈子中,& 运算符被用作最佳实践,因为它是明确的,因此不会因重载而产生任何意外影响。

回答by EFraim

+operator might backfire when strings can be interpreted as numbers. If you don't want nasty surprises use & to concatenate strings.

+当字符串可以解释为数字时,运算符可能会适得其反。如果您不想要令人讨厌的惊喜,请使用 & 连接字符串。

回答by Neal Davis

In some cases the + will throw an exception; for example the following:

在某些情况下,+ 会抛出异常;例如以下内容:

Sub SimpleObject_FloatPropertyChanging(fvalue, cancel)
   'fvalue is a floating point number
   MsgBox "Received Event: " + fvalue
End Sub

You will get an exception when the COM object source fires the event - you must do either of the following:

当 COM 对象源触发事件时,您将收到异常 - 您必须执行以下任一操作:

MsgBox "Received Event: " & fvalue

or

或者

MsgBox "Received Event: " + CStr(fvalue)

It may be best in either case to use CStr(value); but using & per above comments for string concatenation is almost always best practice.

在这两种情况下最好使用CStr(value); 但是使用 & per 上面的注释进行字符串连接几乎总是最佳实践。