解释混淆的条件字符串格式(Explaining confusing conditional string format)

编程入门 行业动态 更新时间:2024-10-25 11:26:35
解释混淆的条件字符串格式(Explaining confusing conditional string format)

一名前同事写道:

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

我阅读了这些文章

代码项目 - 在.NET中自定义字符串格式 MSDN - 自定义数字格式字符串

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

我对这个字符串格式非常好奇。 有人可以解释这种行为吗? 作者不再和我们一起工作。

An ex-coworker wrote this:

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

I read articles like these

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

But I don't still get it how that format works. Obviously I can see the output but I don't understand this part {0:#;;} and the second one. I want to do the same thing for specifying ages (year, years...)

I'm very curious about this string format. Can someone can explain this behavior? The author does not work with us anymore.

最满意答案

这是一个自定义的数字格式字符串 ,基本上 - 但是一个很奇怪的,说实话。 实际上,它是其中的两个:

#;; records;no records;record

在每种情况下,由于有两个部分分隔符 (分号),因此您有三个部分:

第一部分适用于正值,第二部分适用于负值,第三部分适用于零。

开发人员使用rows - 1作为要由第二个格式字符串格式化的值会使情况更加复杂,因此它确实是:

records rows是否大于1(因此rows - 1是正数) no records如果rows等于0(所以rows - 1是负的) record rows是否等于1(因此rows - 1为零)

如果rows是正值,则第一个格式字符串包含rows的值(由于# )。 所以总体结果是:

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

就我个人而言,我会为此使用条件运算符,或者如果/ else语句 - 使用自定义数字格式字符串最糟糕的方式是“聪明”的...

This is a custom numeric format string, basically - but a pretty odd one, to be honest. In fact, it's two of them:

#;; records;no records;record

In each case, you've got three sections, due to having two section separators (the semi-colons):

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

Your situation is further complicated by the developer using rows - 1 as the value to be formatted by the second format string, so it's really:

records if rows is greater than 1 (so rows - 1 is positive) no records if rows is equal to 0 (so rows - 1 is negative) record if rows is equal to 1 (so rows - 1 is zero)

And the first format string only includes the value of rows (due to the #) if rows is positive. So the overall result is:

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

Personally I would have either used a conditional operator for that, or if/else statements - using a custom numeric format string is "clever" in the worst way...

更多推荐

本文发布于:2023-07-29 15:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1317600.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   条件   格式   Explaining   format

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!