【问题标题】:C# interpolated string with conditional-operator [duplicate]带有条件运算符的 C# 插值字符串 [重复]
【发布时间】:2016-02-02 02:35:43
【问题描述】:

我尝试在插值字符串中使用条件运算符,但因为它有一个冒号,编译器认为冒号后面是一个格式字符串。

$"test {foo ? "foo is true" : "foo is false"}";

如何使用这种类型的语句? 我唯一想到的是这样的:

var fooString = foo ? "foo is true" : "foo is false";
$"test {fooString}";

【问题讨论】:

标签: c# conditional-operator string-interpolation


【解决方案1】:
$"test {(foo ? "foo is true" : "foo is false")}";   

括号内的代码返回一个变量,这是大括号内唯一允许的内容。冒号':'是字符串插值中的特殊字符,需要用括号括起来。

【讨论】:

    【解决方案2】:

    您需要将字符串放在{} 内的括号中,因此:{(1 == 1 ? "yes" : "no")}

    【讨论】:

    • 注意括号!谢谢
    猜你喜欢
    • 2020-10-06
    • 2018-01-08
    • 2015-02-14
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 2012-10-09
    • 2020-11-22
    • 1970-01-01
    相关资源
    最近更新 更多