小编典典

为什么使用 String.Format?

all

为什么有人会String.Format在 C# 和 VB .NET 中使用而不是串联运算符(&在 VB 和+C# 中)?

主要区别是什么?为什么大家对使用如此感兴趣String.Format?我很好奇。


阅读 56

收藏
2022-08-19

共1个答案

小编典典

我可以看到几个原因:

可读性

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.
2022-08-19