关于c#:如何在插值字符串中使用三元运算符?

How to use the ternary operator inside an interpolated string?

我不明白为什么这段代码不能编译:

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

如果我把它分开,它会很好地工作:

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


按:《文档

The structure of an interpolated string is as follows:

$"{ }"

问题是,结肠是denote格式,样

1
Console.WriteLine($"Time in hours is {hours:hh}")

那么,答案是:TL;博士在parenthesis WRAP的条件。

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