在String.Format()中显式转换int的原因是什么

Ben*_*enR 3 c#

在我遇到的大多数代码中,他们在使用String.Format()时显式地将int或其他数字转换为字符串,尽管从我注意到它没有必要.是否有一些我缺少的东西需要在将数字用作字符串之前将数字显式转换为字符串?

明确:

int i = 13;
string example = String.Format("If a Friday lands on the {0}th of the month, it is generally considered to be an unlucky day!",
                               i.ToString());
Run Code Online (Sandbox Code Playgroud)

产生example如下:"If a Friday lands on the 13th of the month, it is generally considered to be an unlucky day!"

不明确的:

int i = 13;
string example = String.Format("If a Friday lands on the {0}th of the month, it is generally considered to be an unlucky day!",
                                i);
Run Code Online (Sandbox Code Playgroud)

产生example为:( "If a Friday lands on the 13th of the month, it is generally considered to be an unlucky day!"与显式转换相同).那么为什么我看到的大多数编码器会这样做呢?

Jon*_*eet 7

如果您使用隐式转换,intobject首先将其装箱.这是一个微小的性能影响,但有些人似乎认为很重要,并可能解释代码.

事实上,杰弗里里希特通过C#在其他优秀的CLR中写到了这一点(鼓励使用这类东西).这让我很烦,我在博客上写了 :)

当然在某些地方,拳击可能是相关的 - 但考虑到string.Format需要走格式字符串并做各种其他事情,我不会指望它在这里很重要......那就是在你考虑你是什么之前接下来要做的字符串:)