我几次偶然发现了一个内插字符串的问题.
I have stumbled upon one issue with interpolated strings for a several times now.
请考虑以下情况:
double number = 123.4567; var str = $"{{{number:F2}}}"; //I want to get "{123.45}" Console.WriteLine(str); // Will print "{F2}"起初有点令人惊讶,但是一旦您意识到花括号是如何配对的,就很有意义了.以下两个大括号是插值字符串中单个大写的转义序列.因此,插值表达式的左括号与字符串中的最后一个花括号配对.
A little surprising at first but once you realize how the curly brackets are paired it makes sense. Two following curly brackets are an escape sequence for a single curly in the interpolated string. So the opening bracket of the interpolated expression is paired with the last curly in the string.
___pair____ | | $"{{{number:F2}}}";现在,您可以执行以下操作来中断转义序列:
Now you could do the following to break the escape sequence:
var str = $"{{{number:F2} }}"; // This will be "{123.45 }"请注意此方法将空格字符添加到输出中.(不理想)
Notice the space character this approach adds to the output. (Not ideal)
我的问题:
让我们说我想使用单个内插字符串来获取确切的输出"{123.45}"
Lets say I want to use a single interpolated string to get exactly the output "{123.45}"
如果不进行以下操作,这完全有可能吗?
Is this at all possible without doing something hackish like the following?
var s = $"{{{number:F2}{'}'}"; 推荐答案假设不需要使用命名格式字符串,则可以使用:
Assuming that it is not required to use a named format string, you can use:
var s = $"{{{number:#.#0}}}";更多推荐
插值字符串格式问题
发布评论