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

我很困惑爲何這段代碼不能編譯: 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")}";
相關文章
相關標籤/搜索