+和&之间的区别,用于在VB.NET中连接字符串

Rob*_* P. 66 vb.net string

是什么区别+,并&在VB.NET加入字符串?

Kib*_*bee 86

如果两个操作数都是字符串,则没有区别.但是,如果一个操作数是一个字符串,而一个是数字,那么您遇到问题,请参阅下面的代码.

"abc" + "def" = "abcdef"
"abc" & "def" = "abcdef"
"111" + "222" = "111222"
"111" & "222" = "111222"
"111" & 222 = "111222"
"111" + 222 = 333
"abc" + 222 = conversion error
Run Code Online (Sandbox Code Playgroud)

因此,我建议在&连接时始终使用,因为您可能尝试将整数,浮点数,十进制连接到字符串,这将导致异常,或者充其量,不执行您可能希望它执行的操作.

  • 或者始终强制执行Option Strict On,在这种情况下,您永远不必担心它.Option Strict On还有许多其他优点:http://stackoverflow.com/questions/222370/option-strict-on-and-net-for-vb6-programmers (11认同)
  • 为了完整起见,当你执行"abc"和222`(`"abc222"`)时,还应该注意返回的内容. (5认同)
  • 字符串连接的`&`有问题.来自[文档](http://msdn.microsoft.com/en-us/library/te2585xw.aspx)"&运算符总是将其操作数扩展为String,而不管Option Strict的设置如何".因此,例如`"Hello"&2.5`将使用区域设置将2.5静音转换为字符串(您可能会得到"2.5"或"2,5"`).好吧,如果这是你想要的.我宁愿被迫明确指定. (3认同)
  • 让我提一下倒数第二行中的“333”实际上是“System.Double”类型。 (2认同)

Guf*_*ffa 13

&运算符总是确保两个操作数都是字符串,而+运算符找到与操作数匹配的重载.

表达式1 & 2给出值"12",而表达式1 + 2给出值3.

如果两个操作数都是字符串,则结果没有区别.


Ali*_*tad 8

没有.

如下所示.这两行代码完全编译为相同的IL代码:

Module Module1

    Sub Main()
        Dim s1 As String = "s1"
        Dim s2 As String = "s2"
        s2 += s1
        s1 &= s2
    End Sub

End Module
Run Code Online (Sandbox Code Playgroud)

编译成(注释System.String::Concat):

.method public static void  Main() cil managed
{
.entrypoint
.custom instance void [mscorlib]System.STAThreadAttribute::.ctor() = ( 01 00 00 00 )
// Code size       31 (0x1f)
.maxstack  2
.locals init ([0] string s1,
       [1] string s2)
IL_0000:  nop
IL_0001:  ldstr      "s1"
IL_0006:  stloc.0
IL_0007:  ldstr      "s2"
IL_000c:  stloc.1
IL_000d:  ldloc.1
IL_000e:  ldloc.0
IL_000f:  call       string [mscorlib]System.String::Concat(string,
                                                          string)
IL_0014:  stloc.1
IL_0015:  ldloc.0
IL_0016:  ldloc.1
IL_0017:  call       string [mscorlib]System.String::Concat(string,
                                                          string)
IL_001c:  stloc.0
IL_001d:  nop
IL_001e:  ret
} // end of method Module1::Main
Run Code Online (Sandbox Code Playgroud)