字符串插值 C#:冒号和分号功能的文档

String interpolation C#: Documentation of colon and semicolon functionality

我找到了这个 FizzBu​​zz 测试的 codegolf 答案,仔细检查后我意识到我不知道它到底是如何工作的,所以我开始调查:

for(int i=1; i<101;i++)
    System.Console.Write($"{(i%3*i%5<1?0:i):#}{i%3:;;Fizz}{i%5:;;Buzz}\n");

我把它放到 dotnetfiddle 中并建立了第一部分工作如下:

{(BOOL?0:i):#}

当BOOL为真时,则条件表达式returns0否则为数。

但是,除非是 <> 0,否则不会返回该号码。我猜这是 :# 个字符的工作。我找不到有关 :# 字符工作原理的任何文档。任何人都可以解释 colon/hash 或指出正确的方向吗?

第二部分:

{VALUE:;;Fizz}

VALUE = 0 时,则不打印任何内容。我假设这是由第一个 ; 字符 [end statement] 决定的。第二个 ; 字符确定“如果 VALUE <> 0 然后打印我之后的内容。”

同样,有没有人有关于在字符串插值中使用 分号 的文档,因为我找不到任何有用的东西。

感谢所有评论者!快速响应。

这里定义#(自定义说明符)

https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings#the--custom-specifier

The "#" custom format specifier serves as a digit-placeholder symbol. If the value that is being formatted has a digit in the position where the "#" symbol appears in the format string, that digit is copied to the result string. Otherwise, nothing is stored in that position in the result string. Note that this specifier never displays a zero that is not a significant digit, even if zero is the only digit in the string. It will display zero only if it is a significant digit in the number that is being displayed.

;在这里定义(Section Seperator):

https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings#the--section-separator

The semicolon (;) is a conditional format specifier that applies different formatting to a number depending on whether its value is positive, negative, or zero. To produce this behavior, a custom format string can contain up to three sections separated by semicolons...

这些都包含在 String Interpolation documentation, especially the section on the Structure of an Interpolated String 中,其中包括:

{<interpolatedExpression>[,<alignment>][:<formatString>]}

以及对这三个部分中每个部分的更详细描述。

该结构的格式字符串部分在单独的页面上定义,您可以在其中使用 standard and custom formats for numeric types as well as standard and custom formats for date and time types. There are also options for Enum values, and you can even create your own custom format provider

值得一看自定义格式提供程序文档,因为它也会引导您进入 FormattableString type. This isn't well-covered by the documentation, but my understanding is this type may in theory allow you to avoid re-parsing the interpolated string for each iteration when used in a loop, thus potentially improving performance (though in practice, there's no difference at this time). I've written about this before,我的结论是 MS 需要以更好的方式将其构建到框架中。