字符串操作与和放大器;或+在VB.NET [英] String manipulation with & or + in VB.NET

查看:118
本文介绍了字符串操作与和放大器;或+在VB.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到一些程序员使用&安培; + 字符串处理。

I have seen several programmers use & and + for string manipulation.

如:

dim firstvar as string
dim secondvar as string
dim thirdvar as string

thirdvar = firstvar & secondvar

或者是:

thirdvar = firstvar + secondvar

什么关系呢?如果是这样,为什么?

Does it matter? If so, why?

推荐答案

+ &安培; 运营商的没有的相同的VB.NET。

The + and & operators are not identical in VB.NET.

使用&安培; 运算符表示你的意图来连接字符串,而 + 运算符表示你的意图添加数字。使用&安培; 运营商将经营两侧转换成字符串。当已经混合类型(的前pression一侧是一个字符串,另一种是一个数字),您的操作者的使用将确定结果。

Using the & operator indicates your intention to concatenate strings, while the + operator indicates your intention to add numbers. Using the & operator will convert both sides of the operation into strings. When you have mixed types (one side of the expression is a string, the other is a number), your usage of the operator will determine the result.

1 + "2" = 3 'This will cause a compiler error if Option Strict is on'
1 & "2" = "12"
1 & 2 = "12"
"text" + 2 'Throws an InvalidCastException since "text" cannot be converted to a Double'

所以,我的准则(除了避免混合类型那样)是使用&安培; 连接字符串的时候,只是为了确保你的意图是明确的编译器,避免无法找到的使用 + 运算符连接涉及到的bug。

So, my guideline (aside from avoiding mixing types like that) is to use the & when concatenating strings, just to make sure your intentions are clear to the compiler, and avoid impossible-to-find bugs involving using the + operator to concatenate.

这篇关于字符串操作与和放大器;或+在VB.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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