How to use the ternary operator inside an interpolated string?

半腔热情 提交于 2019-11-26 04:38:45

问题


I\'m confused as to why this code won\'t compile:

var result = $\"{fieldName}{isDescending ? \" desc\" : string.Empty}\";

If I split it up, it works fine:

var desc = isDescending ? \" desc\" : string.Empty;
var result = $\"{fieldName}{desc}\";

回答1:


According to the documentation:

The structure of an interpolated string is as follows:

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

The problem is that the colon is used to denote formatting, like:

Console.WriteLine($"The current hour is {hours:hh}")

The solution is to wrap the conditional in parenthesis:

var result = $"Descending {(isDescending ? "yes" : "no")}";


来源:https://stackoverflow.com/questions/31844058/how-to-use-the-ternary-operator-inside-an-interpolated-string

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