首页 文章

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

提问于
浏览
308

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

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

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

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

1 回答

  • 532

    根据documentation

    插值字符串的结构如下:$“{<interpolation-expression> <optional-comma-field-width> <optional-colon-format>}”

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

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

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

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

相关问题