本文介绍了为什么要使用 String.Format?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么有人会在 C# 和 VB .NET 中使用 String.Format
而不是连接运算符(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);
对比:
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);
对比:
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.
对比:
_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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!