【问题标题】:How to use the ternary operator inside an interpolated string?如何在插值字符串中使用三元运算符?
【发布时间】:2015-10-28 21:51:44
【问题描述】:

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

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

如果我把它分开,它工作正常:

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

【问题讨论】:

标签: c# .net ternary-operator string-interpolation c#-6.0


【解决方案1】:

根据documentation

内插字符串的结构如下:

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

问题是冒号是用来表示格式的,比如:

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

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

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

【讨论】:

  • 当您需要使用嵌套插值字符串时,更有趣的示例是:Console.WriteLine($"Cargo Weight: {(ship.WeightAvailable ? $"{ship.Weight:0.00}" : "n/a")}");
  • 另一个例子,三元 if 在条件中使用字符串插值: var foo = $"{x.Title} {(!string.IsNullOrEmpty(x.SubTitle) ? $"({x.SubTitle} )" : string.Empty)}";
  • @Jan 即使您给出的示例也无法编译,但 ReSharper 可以毫无问题地消除歧义(因为它知道提供代码修复)。
  • @MgSam 如果你告诉错误和你的开发设置会有所帮助。我使用 VS2019 和 VS2022 再次测试了我的示例(复制/粘贴),使用 .NET Core 2 到 .NET Core 6 以及 .NET 2 到 .NET 4.8。所有编译都很好(如果你有一个 Ship 类,当然还有 bool WeighAvailabledouble Weight 公共属性/属性)。
猜你喜欢
  • 1970-01-01
  • 2016-09-09
  • 1970-01-01
  • 2020-09-17
  • 2014-02-19
  • 2017-06-11
  • 2020-11-22
  • 2012-12-19
  • 2016-06-18
相关资源
最近更新 更多