为什么有人会String.Format
在 C# 和 VB .NET 中使用而不是串联运算符(&
在 VB 和+
C# 中)?
主要区别是什么?为什么大家对使用如此感兴趣String.Format
?我很好奇。
为什么有人会String.Format
在 C# 和 VB .NET 中使用而不是串联运算符(&
在 VB 和+
C# 中)?
主要区别是什么?为什么大家对使用如此感兴趣String.Format
?我很好奇。
我可以看到几个原因:
可读性
string s = string.Format("Hey, {0} it is the {1}st day of {2}. I feel {3}!", _name, _day, _month, _feeling);
与:
string s = "Hey," + _name + " it is the " + _day + "st day of " + _month + ". I feel " + feeling + "!";
格式说明符 (这包括您可以编写自定义格式化程序的事实)
string s = string.Format("Invoice number: {0:0000}", _invoiceNum);
与:
string s = "Invoice Number = " + ("0000" + _invoiceNum).Substr(..... /*can't even be bothered to type it*/)
字符串模板持久性
如果我想在数据库中存储字符串模板怎么办?使用字符串格式:
_id _translation
1 Welcome {0} to {1}. Today is {2}.
2 You have {0} products in your basket.
3 Thank-you for your order. Your {0} will arrive in {1} working days.
与:
_id _translation
1 Welcome
2 to
3 . Today is
4 .
5 You have
6 products in your basket.
7 Someone
8 just shoot
9 the developer.
除了更易于阅读和添加更多运算符之外,如果您的应用程序是国际化的,这也是有益的。很多时候,变量是数字或关键词,它们对于不同的语言会有不同的顺序。通过使用 String.Format,您的代码可以保持不变,而不同的字符串将进入资源文件。所以,代码最终会是
String.Format(resource.GetString("MyResourceString"), str1, str2, str3);
虽然您的资源字符串最终成为
英语: "blah blah {0} blah blah {1} blah {2}"
俄语: "{0} blet blet blet {2} blet {1}"
俄语可能对如何处理事物有不同的规则,因此顺序不同或句子结构不同。
首先,我发现
string s = String.Format(
"Your order {0} will be delivered on {1:yyyy-MM-dd}. Your total cost is {2:C}.",
orderNumber,
orderDeliveryDate,
orderCost
);
比读、写和维护容易得多
string s = "Your order " +
orderNumber.ToString() +
" will be delivered on " +
orderDeliveryDate.ToString("yyyy-MM-dd") +
"." +
"Your total cost is " +
orderCost.ToString("C") +
".";
看看下面的可维护性如何
string s = String.Format(
"Year = {0:yyyy}, Month = {0:MM}, Day = {0:dd}",
date
);
在你必须重复date
三遍的替代方案上。
其次,提供的格式说明String.Format
符以一种比简单的旧连接更容易阅读、编写和维护的方式为您提供了极大的字符串输出灵活性。此外,使用String.Format
.
第三,当性能确实重要时,String.Format
将优于串联。在幕后它使用了一个StringBuilder
并避免了Schlemiel the Painter 问题。
几个原因:
String.Format()
非常强大。您可以在格式字符串中使用简单的格式指示符(如固定宽度、货币、字符长度等)。您甚至可以为扩展枚举、将特定输入映射到更复杂的输出或本地化等内容创建自己的格式提供程序。String.Format()
通常更快,因为它StringBuilder
在后台使用了一个高效的状态机,而 .Net 中的字符串连接相对较慢。对于小字符串,差异可以忽略不计,但随着字符串大小和替换值数量的增加,差异会很明显。String.Format()
实际上对于许多程序员来说更熟悉,尤其是那些来自使用旧 Cprintf()
函数变体的背景的程序员。最后,别忘了StringBuilder.AppendFormat()
。 String.Format()
实际上在幕后使用这种方法*,StringBuilder
直接进入可以给你一种混合方法:显式使用.Append()
(类似于连接)用于大字符串的某些部分,并.AppendFormat()
在其他部分使用。
* [编辑] 原始答案现在已有 8 年历史,从那以后,我看到一个迹象表明,当将字符串插值添加到 .Net 时,这可能已经发生了变化。但是,我还没有返回参考源来验证更改。
String.Format
除了连接运算符之外,还添加了许多选项,包括指定添加到字符串中的每个项目的特定格式的能力。
有关可能的详细信息,我建议阅读 MSDN 上标题为Composite Formatting的部分。它解释了String.Format
(以及xxx.WriteLine
支持复合格式的其他方法)相对于普通连接运算符的优势。
这个问题的性能方面有一些有趣的东西
但是,我个人仍然会推荐string.Format
,除非出于可读性原因性能至关重要。
string.Format("{0}: {1}", key, value);
比可读性强
key + ": " + value
例如。还提供了很好的关注点分离。意味着你可以拥有
string.Format(GetConfigValue("KeyValueFormat"), key, value);
然后将您的键值格式从"{0}: {1}"
变为"{0} - {1}"
更改为配置更改而不是代码更改。
string.Format
它还内置了一堆格式规定,整数,日期格式等。
不宜写成这样的字符串的一个原因是'string +"Value"+ string'
本地化。在发生本地化的情况下,我们希望本地化字符串的格式正确,这可能与编码的语言非常不同。
例如,我们需要用不同的语言显示以下错误:
MessageBox.Show(String.Format(ErrorManager.GetError("PIDV001").Description, proposalvalue.ProposalSource)
在哪里
'ErrorCollector.GetError("ERR001").ErrorDescription'
返回一个字符串,如"Your ID {0} is not valid"
. 此消息必须以多种语言本地化。在这种情况下,我们不能在 C# 中使用 +。我们需要遵循 string.format。