在 C# 中将整数添加到字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9418815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:20:37  来源:igfitidea点击:

Adding integers to strings in C#

c#c#-4.0

提问by A.R.

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";

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

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

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

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)?

其中整数转换为字符串。以前的版本是否一直可用,我错过了它,还是它是 C# 4 的新版本(我现在正在使用它)?

采纳答案by BrokenGlass

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 objectinstance. Internally it will call the object's ToString()method before concatenating.

这一直存在。的+相当于string.Concat()如果操作数中的至少一个是一个字符串。string.Concat()有一个带object实例的重载。在内部,它将ToString()在连接之前调用对象的方法。

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

在 C# 规范中找到相关部分 - 第 7.7.4 节加法运算符:

String concatenation:

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

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.

字符串连接

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

当一个或两个操作数都是字符串类型时,二元 + 运算符执行字符串连接。如果字符串连接的操作数为空,则替换为空字符串。否则,通过调用从类型对象继承的虚拟 ToString 方法,将任何非字符串参数转换为其字符串表示形式。如果 ToString 返回 null,则替换为空字符串。

回答by Joe

Of course, the best answer is to use some form of:

当然,最好的答案是使用某种形式:

String.Format("{0},{1}", "123", 4);