带条件运算符的C#插值字符串[duplicate]

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

这个问题在这里已有答案:

我试图在插值字符串中使用条件运算符,但由于它中有冒号,编译器认为在冒号后出现格式字符串。

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

我该如何使用这种声明?我想到的唯一一件事是这样的:

var fooString = foo ? "foo is true" : "foo is false";
$"test {fooString}";
c# conditional-operator string-interpolation
2个回答
71
投票

你需要将字符串放在{}中的括号中,所以:{(1 == 1 ? "yes" : "no")}


6
投票
$"test {(foo ? "foo is true" : "foo is false")}";   

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

© www.soinside.com 2019 - 2024. All rights reserved.