我已经看到一些程序员使用&安培;
和 +
字符串处理。
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.