c# - 解释令人困惑的条件字符串格式

一位前同事写道:

String.Format("{0:#;;} {1:records;no records;record}", rows, rows - 1);
//Rows is a integer value

我读过这样的文章

Code Project - Custom String Formatting in .NET
MSDN - Custom Numeric Format Strings

但我仍然不明白这种格式是如何工作的。显然我可以看到输出,但我不明白这部分 {0:#;;} 和第二部分。我想为指定年龄(年,年...)做同样的事情

我对这种字符串格式很好奇。有人可以解释这种行为吗?作者不再与我们合作。

最佳答案

这是 custom numeric format string ,基本上 - 但说实话,这很奇怪。其实就是两个:

#;;
records;no records;record

在每种情况下,您都有三个部分,因为有两个 section separators (分号):

The first section applies to positive values, the second section applies to negative values, and the third section applies to zeros.

开发人员使用 rows - 1 作为要由第二个格式字符串格式化的值,使您的情况更加复杂,所以它真的是:​​

  • records 如果 rows 大于 1(所以 rows - 1 为正数)
  • no records 如果 rows 等于 0(所以 rows - 1 为负数)
  • record 如果 rows 等于 1(所以 rows - 1 为零)

并且第一个格式字符串only包含rows的值(由于#)如果rows是积极的。所以总体结果是:

Rows     Result
   2     2 records  (ditto for other values greater than 1)
   1     1 record
   0     no records

就我个人而言,我要么为此使用条件运算符,要么使用 if/else 语句 - 使用自定义数字格式字符串在最糟糕的情况下是“聪明的”......

https://stackoverflow.com/questions/25628226/

相关文章:

java - 将 lenient 设置为 false 时的 SimpleDateFormat 异常

excel - 如何通过VBA代码获取Excel 2012条件格式的色标制作的颜色

c# - 如果语句突然被 Visual Studio 2010 在下一行格式化

c# - 使用 string.format 和 List.Count() 进行动态字符串格式化

javascript - Kendo UI 货币格式

html - 如何让 IntelliJ IDEA 保持 HTML 嵌套选项卡?

excel - Vba检查单元格中是否部分粗体

android - Eclipse AndroidManifest.xml 格式

android - 对话框中忽略的 Html 格式标记

java - 从java中的字符串解析带有正/负前缀的数字