串联运算符 (Visual Basic)Concatenation Operators in Visual Basic

串联运算符将多个字符串联接为一个字符串。Concatenation operators join multiple strings into a single string. 有两种串联运算符:+&There are two concatenation operators, + and &. 这两种串联运算符都执行基本的串联运算,如下面的示例所示。Both carry out the basic concatenation operation, as the following example shows.

Dim x As String = "Mic" & "ro" & "soft"
Dim y As String = "Mic" + "ro" + "soft"
' The preceding statements set both x and y to "Microsoft".

这两种运算符还可以串联 String 变量,如下面的示例所示。These operators can also concatenate String variables, as the following example shows.

Dim a As String = "abc"
Dim d As String = "def"
Dim z As String = a & d
Dim w As String = a + d
' The preceding statements set both z and w to "abcdef".

两种串联运算符之间的区别Differences Between the Two Concatenation Operators

+ 运算符的主要目的是添加两个数字。The + Operator has the primary purpose of adding two numbers. 然而,它还可以将数值操作数与字符串操作数串联起来。However, it can also concatenate numeric operands with string operands. + 操作数具有一套复杂的规则,用来确定是相加、串联、指示编译器错误还是引发运行时的 InvalidCastException 异常。The + operator has a complex set of rules that determine whether to add, concatenate, signal a compiler error, or throw a run-time InvalidCastException exception.

只为 String 操作数定义& 运算符,并且无论 Option Strict的设置如何,它始终将其操作数扩大到 StringThe & Operator is defined only for String operands, and it always widens its operands to String, regardless of the setting of Option Strict. 对于字符串串联操作,建议使用 & 运算符,原因是它以独占方式为字符串定义,并降低产生意外转换的可能性。The & operator is recommended for string concatenation because it is defined exclusively for strings and reduces your chances of generating an unintended conversion.

性能:字符串和 StringBuilderPerformance: String and StringBuilder

如果你对字符串执行大量操作(如串联、删除或替换),则通过 StringBuilder 命名空间中的 System.Text 类可能会提高性能。If you do a significant number of manipulations on a string, such as concatenations, deletions, and replacements, your performance might profit from the StringBuilder class in the System.Text namespace. 该类采用额外指令来创建和初始化 StringBuilder 对象,并且使用其他指令将其最终值转换为 String,但此时你可能会恢复使用 StringBuilder,因为它的执行速度更快。It takes an extra instruction to create and initialize a StringBuilder object, and another instruction to convert its final value to a String, but you might recover this time because StringBuilder can perform faster.

另请参阅See also