使用 & 进行字符串操作或 + 在 VB.NET 中 [英] String manipulation with & or + in VB.NET

查看:17
本文介绍了使用 & 进行字符串操作或 + 在 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 中相同.

使用 & 运算符表示您打算连接字符串,而 + 运算符表示您打算添加数字.使用 & 运算符会将操作的两边都转换为字符串.当您有混合类型(表达式的一侧是字符串,另一侧是数字)时,您对运算符的使用将决定结果.

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'

所以,我的指导方针(除了避免像那样混合类型)是在连接字符串时使用 & ,只是为了确保编译器清楚您的意图,并避免不可能- 查找涉及使用 + 运算符进行连接的错误.

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.

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

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