3

在我遇到的大多数代码中,他们在使用 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());

产生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);

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

4

3 回答 3

7

如果您使用隐式转换,则将int首先装箱object。这对性能造成的影响很小,但有些人似乎认为这很重要,并且可以解释代码。

事实上,Jeffrey Richter 在他通过 C# 编写的出色的 CLR 中写到了这一点(鼓励使用这种东西)。这让我很恼火,以至于我在博客上写了它:)

当然,在某些地方,拳击可能是相关的——但鉴于string.Format需要遍历格式字符串并做各种其他事情,我不认为它在这里很重要......那是在你考虑你是什么之前接下来将处理字符串:)

于 2013-01-22T20:25:59.530 回答
0

我真的没有理由这样做。String.Format()正如您所指出的那样,既然已经这样做了,那么如果您只是String.Format()照顾它,它就会更紧凑并且 IMO 更容易阅读。

于 2013-01-22T20:24:46.113 回答
0

因为我们习惯了规则,你最好也习惯。String.Format()是一个聪明的方法,不是每个方法。请记住,它String.Format()需要对象,因此您不需要转换,但是如果您这样做,您仍然会发送一个对象。

于 2013-01-22T20:29:40.437 回答