简体   繁体   English

对Object.ToString()的冗余调用

[英]Redundant Call to Object.ToString()

I have a function that takes, amongst others, a parameter declared as int privateCount . 我有一个函数,其中包括一个声明为int privateCount的参数。 When I want to call ToString() on this param, ReSharper greys it out and marks it as a redundant call. 当我想在这个参数上调用ToString()时,ReSharper将其灰显并将其标记为冗余调用。 So, curious as I am, I remove the ToString(), and the code still builds! 所以,好像我一样,我删除了ToString(),代码仍然构建!

How can a C# compiler allow this, where str is a string? C#编译器如何允许这样,其中str是一个字符串?

str += privateCount + ... str += privateCount + ...

The + operator for string is overloaded to call String.Concat passing in the left and right side of the expression. 字符串的+运算符被重载以调用在表达式的左侧和右侧传递的String.Concat。 Thus: 从而:

string x = "123" + 45;

Gets compiled to: 获取编译为:

String.Concat("123", 45);

Since String.Concat takes in two objects, the right hand side (45) is boxed and then ToString() is called on it. 由于String.Concat接收两个对象,因此右侧(45)被装箱,然后在其上调用ToString()。

Note that this "overloading" is not via operator overloading in the language (aka it's not a method named op_Addition) but is handled by the compiler. 请注意,这种“重载”不是通过语言中的运算符重载(也就是说它不是名为op_Addition的方法),而是由编译器处理。

这不仅是不好的做法,而且性能也较差:整数必须被装箱,因为String.Concat预测了一个对象而int.ToString()不需要装箱。

C# automatically converts the objects to strings for you. C#会自动将对象转换为字符串。 Consider this line of code: 考虑以下代码行:

aString = aString + 23;

This is valid C#; 这是有效的C#; it compiles down to a call to String.Concat(), which takes two objects as arguments. 它编译为String.Concat()的调用,它接受两个对象作为参数。 Those objects are automatically converted to string objects for you. 这些对象会自动转换为字符串对象。

The same thing occurs when you write: 你写的时候会发生同样的事情:

aString += 23;

Again, this compiles down to the same call to String.Concat(); 同样,这将编译为对String.Concat()的相同调用; it's just written differently. 它的写法不同。

This is a valid bad practice, as you must think twice if the variable is a string or an int. 这是一种有效的不良做法,因为如果变量是字符串或int,您必须三思而后行。 What if the variable would be called myInt? 如果变量被称为myInt怎么办?

myInt = myInt + 23;

it is more readable and understandable in this form? 它在这种形式下更具可读性和可理解性?

myInt = mInt + "23";

or even: 甚至:

myInt = string.Format("{0}{1}", myInt, 23);

We know from the code that it is a string and not an integer. 我们从代码中知道它是一个字符串而不是整数。

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

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