将意外的令牌变成三元运算符

问题描述 投票:0回答:2

我想做一个简单的三元操作,如:

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

但我得到了

意外的标记 '{'

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

c# ternary-operator
2个回答
2
投票

您正在使用$ - 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


0
投票

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

progressToBackCheckMedianString = $"{newLine} Medians {(medianInProgressFormattedTime != string.Empty ? $"{newLine} {medianInProgressFormattedTime}{newLine}" : string.Empty)}";
© www.soinside.com 2019 - 2024. All rights reserved.