这个问题在这里已有答案:
我试图在插值字符串中使用条件运算符,但由于它中有冒号,编译器认为在冒号后出现格式字符串。
$"test {foo ? "foo is true" : "foo is false"}";
我该如何使用这种声明?我想到的唯一一件事是这样的:
var fooString = foo ? "foo is true" : "foo is false";
$"test {fooString}";
你需要将字符串放在{}
中的括号中,所以:{(1 == 1 ? "yes" : "no")}
。
$"test {(foo ? "foo is true" : "foo is false")}";
括号内的代码返回一个变量,这是大括号内允许的唯一内容。冒号':'是字符串插值中的特殊字符,因此需要加括号。