在 C# 中将整数添加到字符串 [英] Adding integers to strings in 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()
有一个采用 object
实例的重载.在内部,它会在连接之前调用对象的 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);
二元 + 运算符在其中一个或两个时执行字符串连接操作数是字符串类型.如果字符串连接的操作数是null,一个空字符串被替换.否则,任何非字符串参数通过调用从类型对象继承的虚拟 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.
这篇关于在 C# 中将整数添加到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!