[英]C# string + vs. +=
Why does string += char + int
work differently to string = string + char + int
?为什么
string += char + int
与string = string + char + int
int 的工作方式不同?
char c = '0';
int i = 123;
string s = "";
s += c + i; // Evaluated as s = s + (c + i);
Console.WriteLine($"s: \"{s}\""); // s: "171"
s = "";
s = s + c + i; // Evaluated as s = (s + c) + i;
Console.WriteLine($"s: \"{s}\""); // s: "0123"
Tested on C# 4.0-9.0.在 C# 4.0-9.0 上测试。
As described in C# language reference :如C# 语言参考中所述:
If the return type of the selected operator is implicitly convertible to the type of x, the operation is evaluated as x = x op y, ...
如果所选运算符的返回类型可隐式转换为 x 的类型,则该运算的计算结果为 x = x op y, ...
PS: this is real-life situation: PS:这是现实生活中的情况:
path += Path.AltDirectorySeparatorChar + fileId + ".txt";
int
and char
can be cast to each other in c#. int
和char
可以在 c# 中相互转换。 char
can be added to an int to produce an int, because ( link - emphasis added) char
可以添加到 int 以产生 int,因为( 链接- 强调添加)
The
char
type supports comparison, equality, increment, and decrement operators.char
类型支持比较、相等、递增和递减运算符。 Moreover, for char operands, arithmetic and bitwise logical operators perform an operation on the corresponding character codes and produce the result of the int type .此外,对于 char 操作数,算术和按位逻辑运算符对相应的字符代码执行操作并产生 int 类型的结果。
For example:例如:
'0' + 123
// result: 171
And an int can be converted back into a char:并且 int 可以转换回 char:
(char)48
// result: '0'
So when you try to concatenate with +=
, the int
and char
are evaluated to an int
type since there is nothing telling them to do otherwise.因此,当您尝试与
+=
连接时, int
和char
被评估为int
类型,因为没有什么告诉他们要不然。 Prepend with a string, however:但是,在前面加上一个字符串:
string s += "" + c + i;
// result: "0123"
Now the compiler, reading your expression from left to right, implicitly calls ToString
on c
and i
, so no arithmetic operations occur, only string concatenation (That's why string s = s + c + i
behaved differently).现在编译器从左到右读取您的表达式,隐式调用
c
和i
上的ToString
,因此不会发生算术运算,只有字符串连接(这就是string s = s + c + i
表现不同的原因)。
Per your comment:根据您的评论:
Now I can reformulate my question:) Why
s += c + i
is equivalent tos += (c + i)
instead of(s += c) + i
现在我可以重新提出我的问题了:) 为什么
s += c + i
等价于s += (c + i)
而不是(s += c) + i
Everything after the +=
is evaluated before the concatenation (see Operator precedence and associativity ). +=
之后的所有内容都在连接之前进行评估(请参阅运算符优先级和关联性)。 Think of everything right of the =
as its own variable.将
=
的所有权利都视为它自己的变量。 Essentialy:本质上:
var right = c + i;
var left = s;
s = left + right; // effectively same as s += c + i;
// or
s = s + (c + i /** everything on the right side in order here **/);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.