使用“.ToString()”带有数字变量
将数值转换为 string
时省略 .ToString()
有什么缺点吗?
int i = 1234;
string s;
// Instead of
s = "i is " + i.ToString();
// Writing
s = "i is " + i;
Is there any drawback for omitting .ToString()
while converting numeric values to string
?
int i = 1234;
string s;
// Instead of
s = "i is " + i.ToString();
// Writing
s = "i is " + i;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在这种情况下没有什么区别。
编译为
String.Concat 具有多个重载,并且我相信选择了
Concat(Object, Object)
重载(因为 string 和 int 的唯一共同祖先是 object)。内部实现是这样的:
如果您调用
,那么它会选择
Concat(String, String)
重载,因为两者都是字符串。因此,对于所有实际问题,它本质上都是做同样的事情 - 它隐式调用 i.ToString()。
在上述情况下,我通常会省略 .ToString,因为它只会增加噪音。
It doesn't make a difference in this case.
compiles down to
String.Concat has multiple overloads, and I believe that the
Concat(Object, Object)
overload is chosen (since the only common ancestor of string and int is object).The internal implementation is this:
If you call
then it chooses the
Concat(String, String)
overload since both are strings.So for all practical matters, it's essentially doing the same anyway - it's implicitly calling i.ToString().
I usually omit .ToString in cases like the above because it just adds noise.
尽管事实上它无法编译(至少如果不在第一个
i
前面添加另一个""
就不会使用 Visual Studio 2008),但还是存在差异,具体取决于关于如何使用它(假设它可以工作)以及处理运算符的顺序(在 C# 中,我猜几乎所有语言+
的优先级都高于=
):编辑:
使用更新后的代码,假设您不使用括号对多个非字符串对象/变量进行分组,则没有真正的区别:
Despite the fact it won't compile (at least it won't using Visual Studio 2008 without adding another
""
in front of the firsti
) there ARE differences, depending on how you use it (assuming it would work) and in which order operators are handled (in C# and I guess almost all languages+
has a higher priority than=
):Edit:
With the updated code there's no real difference assuming you don't use brackets to group several non-string objects/variables:
我能想到的唯一缺点是您可以将其他参数添加到 ToString() 中。
但在大多数情况下,您可以将字符串与 int 连接起来,我认为更好的解决方案是使用 string.Format() :
在您的情况下,这种方式更好并不那么明显,但是您开始考虑添加适当的标点符号(
i is {0}.
),以其他方式稍微改变输出,或者支持本地化,这种方式的优点变得显而易见。The only drawback I can think of is that you can put additional parameters to
ToString()
.But in most cases where you could concatenate string with an int, I think the better solution is to use
string.Format()
:In your case, it's not as obvious that this way is better, but you start thinking about adding proper punctuation (
i is {0}.
), changing the output slightly in some other way, or supporting localization, the advantages of this way become clear.当 Option Strict 启用时(C# 的默认设置),赋值
s = i
将不会编译。The assignment
s = i
will not compile when Option Strict is on (default for C#).