在带有格式字符串的大括号之后,如何转义内插字符串中的大括号?
How do I escape a brace in an interpolated string, after a brace with a format string?
以下崩溃:
$"{{{DayOfWeek.Friday:d}}}"
如果我在第一个右大括号后放一个 space,它可以工作,但我不想在那里放一个 space。
所以 2 个问题:
- 为什么它会崩溃,而不是将最后 2 个大括号视为文字大括号?
- 我怎样才能做我想做的事?
请查看 Escaping Braces 文档
For example, consider the format item "{{{0:D}}}", which is intended
to display an opening brace, a numeric value formatted as a decimal
number, and a closing brace. However, the format item is actually
interpreted in the following manner: The first two opening braces
("{{") are escaped and yield one opening brace. The next three
characters ("{0:") are interpreted as the start of a format item. The
next character ("D") would be interpreted as the Decimal standard
numeric format specifier, but the next two escaped braces ("}}") yield
a single brace. Because the resulting string ("D}") is not a standard
numeric format specifier, the resulting string is interpreted as a
custom format string that means display the literal string "D}".
这正是你的情况,结果你得到了不正确的格式说明符。
对于您的代码,您可以尝试使用旧的 string.Format
string.Format("{0}{1:d}{2}", "{", DayOfWeek.Friday, "}");
以下崩溃:
$"{{{DayOfWeek.Friday:d}}}"
如果我在第一个右大括号后放一个 space,它可以工作,但我不想在那里放一个 space。
所以 2 个问题:
- 为什么它会崩溃,而不是将最后 2 个大括号视为文字大括号?
- 我怎样才能做我想做的事?
请查看 Escaping Braces 文档
For example, consider the format item "{{{0:D}}}", which is intended to display an opening brace, a numeric value formatted as a decimal number, and a closing brace. However, the format item is actually interpreted in the following manner: The first two opening braces ("{{") are escaped and yield one opening brace. The next three characters ("{0:") are interpreted as the start of a format item. The next character ("D") would be interpreted as the Decimal standard numeric format specifier, but the next two escaped braces ("}}") yield a single brace. Because the resulting string ("D}") is not a standard numeric format specifier, the resulting string is interpreted as a custom format string that means display the literal string "D}".
这正是你的情况,结果你得到了不正确的格式说明符。
对于您的代码,您可以尝试使用旧的 string.Format
string.Format("{0}{1:d}{2}", "{", DayOfWeek.Friday, "}");