【问题标题】:Can C# 8 new switch replace a code block containing multiple ? : ? : expressions?C# 8 新开关可以替换包含多个的代码块吗? : ? : 表达式?
【发布时间】:2019-12-28 10:42:58
【问题描述】:

这是我现在正在做的一个例子:

return
    shpc == 0 ? "Currently, based on your selection below, you have not yet identified any hidden cards in your card deck." :
    shpc == 1 ? "Currently, based on your selection below, you have one hidden card in your card deck." :
                $"Currently, based on your selection below, you have {shpc} hidden cards in your card deck. These will not be visible.";

代码词,但对添加到 switch 的内容不太了解我想知道这是否也可以使用 switch 表达式来完成?

【问题讨论】:

  • 你可以用“经典”开关替换它,不需要c#8开关的新奇特性
  • @GianPaolo switch 表达式比 switch 语句更简洁,更易于使用,在 case 块中有很多 returns 或直接变量赋值。

标签: c# switch-statement c#-8.0


【解决方案1】:

试试这个

return shpc switch 
{
    0 => "Currently, based on your selection below, you have not yet identified any hidden cards in your card deck.",
    1 => "Currently, based on your selection below, you have one hidden card in your card deck.",
    _ => $"Currently, based on your selection below, you have {shpc} hidden cards in your card deck. These will not be visible."
};

【讨论】:

    【解决方案2】:

    肯定的:

    return shpc switch 
    {
        0 => "Currently, based on your selection below, you have not yet identified any hidden cards in your card deck.",
        1 => "Currently, based on your selection below, you have one hidden card in your card deck.",
        _ => $"Currently, based on your selection below, you have {shpc} hidden cards in your card deck. These will not be visible."
    };
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-16
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-05
      相关资源
      最近更新 更多