【问题标题】:String Interpolation inside String Interpolation in C# results in compiler error [duplicate]C#中字符串插值内的字符串插值导致编译器错误[重复]
【发布时间】:2017-06-05 08:58:52
【问题描述】:

以下 C# 表达式导致我的程序出现编译器错误:

$"Getting image from {location.IsLatitudeLongitude ? $"{location.Latitude} - {location.Longitude}" : location.Location}."

不应该像那样使用字符串插值吗?还是不能这样做?

【问题讨论】:

  • 在字符串插值中使用三元运算符有点棘手:我认为您必须添加圆括号。

标签: c# string-interpolation csc


【解决方案1】:

我刚刚测试了这个。正如我所评论的,您需要为 Tenery 运算符使用大括号:

$"Getting image from {(location.IsLatitudeLongitude ? $"{location.Latitude} - {location.Longitude}" : location.Location)}."

【讨论】:

    【解决方案2】:

    根据documentation,在字符串插值中使用三元运算符时需要使用以下格式。

    内插字符串的结构如下:

    $ "{ <interpolation-expression> <optional-comma-field-width> <optional-colon-format> }"
    

    因此,您需要在 { 之后和结束 } 之前添加一组括号,如下所示:

    $"Getting image from {(location.IsLatitudeLongitude ? $"{location.Latitude} - {location.Longitude}" : location.Location)}."
    

    【讨论】:

      猜你喜欢
      • 2019-05-10
      • 2011-07-23
      • 1970-01-01
      • 1970-01-01
      • 2016-09-17
      • 2018-12-12
      • 2017-01-19
      • 1970-01-01
      相关资源
      最近更新 更多