为什么有人会使用String.FormatC#和VB .NET而不是串联运算符(&在VB和+C#中)?
主要区别是什么?为什么每个人都如此感兴趣String.Format?我很好奇.
Moo*_*ice 396
我可以看到很多原因:
可读性
string s = string.Format("Hey, {0} it is the {1}st day of {2}. I feel {3}!", _name, _day, _month, _feeling);
Run Code Online (Sandbox Code Playgroud)
VS:
string s = "Hey," + _name + " it is the " + _day + "st day of " + _month + ". I feel " + feeling + "!";
Run Code Online (Sandbox Code Playgroud)
格式说明符 (这包括您可以编写自定义格式化程序的事实)
string s = string.Format("Invoice number: {0:0000}", _invoiceNum);
Run Code Online (Sandbox Code Playgroud)
VS:
string s = "Invoice Number = " + ("0000" + _invoiceNum).Substr(..... /*can't even be bothered to type it*/)
Run Code Online (Sandbox Code Playgroud)
字符串模板持久性
如果我想在数据库中存储字符串模板怎么办?使用字符串格式:
_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.
Run Code Online (Sandbox Code Playgroud)
VS:
_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.
Run Code Online (Sandbox Code Playgroud)
doo*_*bop 91
除了更容易阅读和添加更多操作符之外,如果您的应用程序是国际化的,这也是有益的.很多时候变量是数字或关键词,对于不同的语言将是不同的顺序.通过使用String.Format,您的代码可以保持不变,而不同的字符串将进入资源文件.所以,代码最终会成为
String.Format(resource.GetString("MyResourceString"), str1, str2, str3);
Run Code Online (Sandbox Code Playgroud)
虽然你的资源字符串最终成为了
英语: "blah blah {0} blah blah {1} blah {2}"
俄语: "{0} blet blet blet {2} blet {1}"
俄罗斯可能对如何处理事情有不同的规则,因此顺序不同或句子结构不同.
jas*_*son 26
首先,我发现
string s = String.Format(
"Your order {0} will be delivered on {1:yyyy-MM-dd}. Your total cost is {2:C}.",
orderNumber,
orderDeliveryDate,
orderCost
);
Run Code Online (Sandbox Code Playgroud)
比阅读,编写和维护更容易
string s = "Your order " +
orderNumber.ToString() +
" will be delivered on " +
orderDeliveryDate.ToString("yyyy-MM-dd") +
"." +
"Your total cost is " +
orderCost.ToString("C") +
".";
Run Code Online (Sandbox Code Playgroud)
看看以下是多么可维护
string s = String.Format(
"Year = {0:yyyy}, Month = {0:MM}, Day = {0:dd}",
date
);
Run Code Online (Sandbox Code Playgroud)
在替代方案中你必须重复date三次.
其次,提供的格式说明符String.Format使您能够以比使用普通旧级联更容易阅读,编写和维护的方式为字符串输出提供极大的灵活性.此外,更容易理解文化问题String.Format.
第三,当性能确实重要时,String.Format将胜过连接.在幕后它使用了一个StringBuilder并避免施莱米尔画家的问题.
Joe*_*orn 17
几个原因:
String.Format()是非常强大的.您可以在格式字符串中使用简单的格式指示符(如固定宽度,货币,字符长度等).您甚至可以为扩展枚举,将特定输入映射到更复杂的输出或本地化等内容创建自己的格式提供程序.String.Format()通常更快,因为它StringBuilder在幕后使用一个有效的状态机,而.Net中的字符串连接相对较慢.对于小字符串,差异可以忽略不计,但随着字符串的大小和替换值的数量增加,它可能是显而易见的.String.Format()实际上对于许多程序员来说更为熟悉,特别是来自使用旧C printf()函数变体的背景的程序员.最后,别忘了StringBuilder.AppendFormat(). String.Format()实际上在幕后使用这种方法*,StringBuilder直接进入可以给你一种混合方法:明确地.Append()对大字符串的某些部分使用(类似于连接),并.AppendFormat()在其他部分使用.
*[edit]原始答案现在已经有8年了,而且我已经看到了当字符串插值被添加到.Net时可能已经改变的迹象.但是,我还没有回到参考源来验证更改.
String.Format 除了连接运算符之外,还添加了许多选项,包括指定添加到字符串中的每个项的特定格式的功能.
有关可能的详细信息,我建议您阅读MSDN上标题为" 复合格式 "的部分.它解释了String.Format(以及xxx.WriteLine支持复合格式化的其他方法)优于普通连接运算符的优点.
| 归档时间: |
|
| 查看次数: |
270851 次 |
| 最近记录: |