Why can't I use the conditional operator in an interpolated string without brackets? [duplicate]

放肆的年华 提交于 2019-12-20 03:27:13

问题


Why can't I use the inline conditional-operator inside a c#-6 string interpolation, without encompassing it within brackets?

and the errors:

As you can see, it appears the parser is having a hard time. Is this a bug, or a feature of the string interpolation mechanism?


回答1:


From MSDN (emphasis mine):

$"{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.

Without the parentheses, the parser is treating the portion after the colon as a format specifier instead (compare the {person.Age:D3} portion of the example above).



来源:https://stackoverflow.com/questions/35649589/why-cant-i-use-the-conditional-operator-in-an-interpolated-string-without-brack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!