如何在内插字符串中使用三元运算符?

How to use the ternary operator inside an interpolated string?

我很困惑为什么这段代码无法编译:

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

如果我把它分开,效果很好:

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

根据 documentation:

The structure of an interpolated string is as follows:

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

问题是冒号是用来表示格式的,比如:

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

解决方法是括号中的条件包裹起来:

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