在插值字符串中编写其他的 C# 代码?

huangapple go评论71阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年4月7日 04:45:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75953627.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定