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

我很困惑为何这段代码不能编译: spa

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

若是我拆分它,它工做正常: code

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

#1楼

根据文件orm

插值字符串的结构以下: 字符串

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

问题是冒号用于表示格式,如: string

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

解决方案是条件括在括号中: it

var result = $"Descending {(isDescending ? "yes" : "no")}";
相关文章
相关标签/搜索