【问题标题】:Getting unexpected token into ternary operator将意外令牌放入三元运算符
【发布时间】:2018-09-18 23:49:07
【问题描述】:

我想做一个简单的三元运算,比如:

   progressToBackCheckMedianString = $"{newLine} Medians {(medianInProgressFormattedTime != string.Empty ? {newLine} {medianInProgressFormattedTime}{newLine} : string.Empty)}" ;

但我得到了

意外的令牌'{'

并且{(medianInProgressFormattedTime != string.Empty ? 标记为红色并带有此错误。我做错了什么?问候

【问题讨论】:

    标签: c# ternary-operator


    【解决方案1】:

    您使用的是$ - string interpolation,它支持高于6.0的c#版本

    {interpolatedExpression}

    大括号在语法中具有特殊含义。

    您的newLine 看起来像一个字符串值。

    去掉newLine之间的{},用+连接字符串值,因为外面已经用大括号了。

    我会用

    string.IsNullOrEmpty
    

    检查字符串值而不是

    medianInProgressFormattedTime != string.Empty
    

    因为medianInProgressFormattedTime 可能是NULL

    string progressToBackCheckMedianString = $"{newLine} Medians{(!string.IsNullOrEmpty(medianInProgressFormattedTime) ? newLine + medianInProgressFormattedTime + newLine : string.Empty)}";
    

    c# Test

    【讨论】:

      【解决方案2】:

      {newLine} {medianInProgressFormattedTime}{newLine}周围添加字符串引号

      progressToBackCheckMedianString = $"{newLine} Medians {(medianInProgressFormattedTime != string.Empty ? $"{newLine} {medianInProgressFormattedTime}{newLine}" : string.Empty)}";
      

      【讨论】:

        猜你喜欢
        • 2018-09-07
        • 1970-01-01
        • 2017-03-05
        • 2011-12-31
        • 1970-01-01
        • 1970-01-01
        • 2017-10-08
        • 2018-08-30
        • 2022-01-11
        相关资源
        最近更新 更多