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)
因此,我建议在&连接时始终使用,因为您可能尝试将整数,浮点数,十进制连接到字符串,这将导致异常,或者充其量,不执行您可能希望它执行的操作.
Guf*_*ffa 13
&运算符总是确保两个操作数都是字符串,而+运算符找到与操作数匹配的重载.
表达式1 & 2给出值"12",而表达式1 + 2给出值3.
如果两个操作数都是字符串,则结果没有区别.
没有.
如下所示.这两行代码完全编译为相同的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)