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

Nat*_*ini 372 .net c# ternary-operator string-interpolation c#-6.0

我很困惑为什么这段代码不能编译:

var result = $"{fieldName}{isDescending ? " desc" : string.Empty}";
Run Code Online (Sandbox Code Playgroud)

如果我拆分它,它工作正常:

var desc = isDescending ? " desc" : string.Empty;
var result = $"{fieldName}{desc}";
Run Code Online (Sandbox Code Playgroud)

Nat*_*ini 655

根据文件:

插值字符串的结构如下:

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

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

Console.WriteLine($"The current hour is {hours:hh}")
Run Code Online (Sandbox Code Playgroud)

所以,tl; dr答案是:将条件括在括号中.

var result = $"Descending {(isDescending ? "yes" : "no")}";
Run Code Online (Sandbox Code Playgroud)

  • 更有趣的例子是当您需要使用嵌套插值字符串时: `Console.WriteLine($"Cargo Weight: {(ship.WeightAvailable ? $"{ship.Weight:0.00}" : "n/a") }");` (10认同)