为什么我不能在没有括号的内插字符串中使用条件运算符?
Why can't I use the conditional operator in an interpolated string without brackets?
为什么我不能在 c#-6 字符串插值中使用内联条件运算符,而不用括号括起来?
和错误:
如您所见,解析器似乎遇到了困难。这是一个错误,还是字符串插值机制的一个特性?
来自 MSDN(强调我的):
$"{person.Name, 20} is {person.Age:D3} year {(p.Age == 1 ? "" : "s")} old."
You do not need to quote the quotation characters within the contained interpolation expressions because interpolated string expressions start with $, and the compiler scans the contained interpolation expressions as balanced text until it finds a comma, colon, or close curly brace. For the same reasons, the last example uses parentheses to allow the conditional expression (p.Age == 1 ? "" : "s")
to be inside the interpolation expression without the colon starting a format specification. Outside of the contained interpolation expression (but still within the interpolated string expression) you escape quotation characters as you normally would.
没有括号,解析器会将冒号后的部分视为 format specifier(比较上面示例的 {person.Age:D3}
部分)。
为什么我不能在 c#-6 字符串插值中使用内联条件运算符,而不用括号括起来?
和错误:
如您所见,解析器似乎遇到了困难。这是一个错误,还是字符串插值机制的一个特性?
来自 MSDN(强调我的):
$"{person.Name, 20} is {person.Age:D3} year {(p.Age == 1 ? "" : "s")} old."
You do not need to quote the quotation characters within the contained interpolation expressions because interpolated string expressions start with $, and the compiler scans the contained interpolation expressions as balanced text until it finds a comma, colon, or close curly brace. For the same reasons, the last example uses parentheses to allow the conditional expression
(p.Age == 1 ? "" : "s")
to be inside the interpolation expression without the colon starting a format specification. Outside of the contained interpolation expression (but still within the interpolated string expression) you escape quotation characters as you normally would.
没有括号,解析器会将冒号后的部分视为 format specifier(比较上面示例的 {person.Age:D3}
部分)。