添加整数转换为字符串在C#

添加整数转换为字符串在C#

问题描述:

最近,我已经被告知,这是可能的串联整数(和其他类型)的字符串,反之亦然,即

Recently I have been informed that it is possible to concatenate integers (and other types) to string and vice versa, i.e.

// x == "1234"
// y == "7890"
string x = "123" + 4;
string y = 7 + "890";

有关某种原因,我不认为这种事情是允许的,所以我一直在使用(因为.NET 2)形式:

For some reason I didn't think this kind of thing was allowed, so I have always been using (since .NET 2) the form:

// x == "1234"
// y == "7890"
string x = "123" + 4.ToString();
string y = 7.ToString() + "890";



其中整数转换为字符串。有前一个版本始终是可用的,我已经错过了,或者是它的东西是新的C#4(这是我现在用的)?

where the integers are converted to strings. Has the former version always been available, and I've missed it, or is it something that is new to C# 4 (which is what I am using now)?

这是一直存在的。在 + 等同于 string.Concat()如果操作数至少有一个是一个字符串。 string.Concat()有一个重载接受一个对象实例。在内部它会调用该对象的的ToString()方法之前串联

This has always been there. The + is equivalent to string.Concat() if at least one of the operands is a string. string.Concat() has an overload that takes an object instance. Internally it will call the object's ToString() method before concatenating.

发现在C#规范的相关章节。 - 7.7.4小节加法运算符:

Found the relevant section in the C# spec - section 7.7.4 Addition operator:

字符串连接

string operator +(string x, string y);
string operator +(string x, object y);
string operator +(object x, string y);

在一个或两个
操作数为string类型时,二元+运算符执行字符串连接。如果字符串连接的一个操作数为
空,空字符串被替换。否则,任何非字符串
参数是通过调用从object类型继承了
虚ToString方法转化为它的字符串表示。如果的ToString
返回null,一个空字符串将被替换。

The binary + operator performs string concatenation when one or both operands are of type string. If an operand of string concatenation is null, an empty string is substituted. Otherwise, any non-string argument is converted to its string representation by invoking the virtual ToString method inherited from type object. If ToString returns null, an empty string is substituted.