简体   繁体   English

将整数转换为字符串“” +1和1.ToString()的区别

[英]Difference between converting integer to string “” +1 and 1.ToString()

What is the difference when I convert integer to string like this way: 这样将整数转换为字符串有什么区别:

string str = "" + 1;


And

string str =1.ToString();

The first method is equivalent to string str = "" + 1.ToString(); 第一种方法等效于string str = "" + 1.ToString(); and uses 2 intermediate strings before producing the result. 并在产生结果之前使用2个中间字符串。 That amounts to 3 strings total: an empty string, "1", and the result of the concatenation, which is also "1". 总计3个字符串:一个空字符串“ 1”和串联结果也为“ 1”。

The second method doesn't use any intermediate string. 第二种方法不使用任何中间字符串。 It's also more readable and clearly expresses your intent (which is to convert the integer into a string). 它也更具可读性,并且清楚地表达了您的意图(即将整数转换为字符串)。

With ToString() you assign a return value of the method. 使用ToString()您可以分配方法的返回值。 By using "" + 1 the ToString() method is called by the CLR. 通过使用"" + 1 ,CLR调用ToString()方法。

See Automatic .ToString()? 看到自动.ToString()吗?

int.ToString() is the tool for converting an integer into a string. int.ToString()是将整数转换为字符串工具。

However, the C# allows you not to call this method when concatenating strings via plus operator , and the framework calls .ToString() instead of you. 然而,C#允许你不通过加运营商连接字符串时,调用此方法,并且该框架调用.ToString()而不是你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM