为什么要使用的String.Format? [英] Why use String.Format?
本文介绍了为什么要使用的String.Format?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么会有人用的String.Format
C#和VB .NET相对于串联运算符(&安培;
VB的 +
在C#中)?
Why would anyone use String.Format
in C# and VB .NET as opposed to the concatenation operators (&
in VB, and +
in C#)?
主要的区别是什么?为什么大家如此热衷于使用的String.Format
?我很好奇。
What is the main difference? Why are everyone so interested in using String.Format
? I am very curious.
推荐答案
我可以看到几个原因:
可读性
string s = string.Format("Hey, {0} it is the {1}st day of {2}. I feel {3}!", _name, _day, _month, _feeling);
VS
string s = "Hey," + _name + " it is the " + _day + "st day of " + _month + ". I feel " + feeling + "!";
格式说明
(这包括可以编写自定义格式的事实)
Format Specifiers (and this includes the fact you can write custom formatters)
string s = string.Format("Invoice number: {0:0000}", _invoiceNum);
VS
string s = "Invoice Number = " + ("0000" + _invoiceNum).Substr(..... /*can't even be bothered to type it*/)
字符串模板持久性
如果我想字符串模板存储在数据库中?与字符串格式化:
What if I want to store string templates in the database? With string formatting:
_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.
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.
这篇关于为什么要使用的String.Format?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文