英文:
Write other C# code in an interpolated string?
问题
string header = $@"Header: {
pageTitle switch
{
"" => ""No title"",
_ => pageTitle
}}";
string header51 = $@"Header: {
(pageTitle5 == """) ? ""No title"" : pageTitle5;
}";
英文:
In C# 11 we can now include newlines in an interpolated string. So we can write code like this:
string pageTitle = "";
string header = $"Header: {
pageTitle switch
{
"" => "No title",
_ => pageTitle
}}";
Is there a way to write other code here beyond the switch statement?
I tried an if
and it tells me that if
is an invalid expression term.
string header51 = $"Header: {
if (pageTitle5 == "")
{
"No title";
}
else
{
pageTitle5;
}
}";
Are there other statements beyond switch that work here?
答案1
得分: 6
每个表达式都能正常工作。在C#中,if
不是一个表达式,而是一个语句。
然而,三元运算符生成一个表达式:
string header51 = $"Header: {
(pageTitle5 == ""
? "No title"
: pageTitle5)
}";
在你的例子中switch
有效,因为你没有使用switch
语句,而是使用了switch
表达式。
英文:
Every expression will work. In C#, if
is not an expression, but a statement.
However, the ternary operator yields an expression:
string header51 = $"Header: {
(pageTitle5 == ""
? "No title"
: pageTitle5)
}";
switch
works in your example, because you do not use the switch
statement but a switch
expression.
答案2
得分: 1
如果您更喜欢使用if else语句,可以像这样编写代码:
string header51 = $"Header:{() =>
{
if (pageTitle5 == "")
{
return "No title";
}
else
{
return pageTitle5;
}
}
}";
这样,您就可以在if else块中进行更多的逻辑操作。
英文:
If you prefer using if else statement, you can write the code like this :
string header51 = $"Header:{() =>
{
if (pageTitle5 == "")
{
return "No title";
}
else
{
return pageTitle5;
}
}
}";
This way you have more flexibility to do extra logics in the if else block
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论