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


408

我对为什么此代码无法编译感到困惑:

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

如果我将其拆分,则可以正常工作:

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



Answers:


722

根据文档

插值字符串的结构如下:

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

问题在于冒号用于表示格式,例如:

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

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

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

2
当您需要使用嵌套插值字符串时,这是一个更有趣的示例: Console.WriteLine($"Cargo Weight: {(ship.WeightAvailable ? $"{ship.Weight:0.00}" : "n/a")}");
Jan
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.