C# 8 新的 switch 能否替换包含多个 ? : 表达式的代码块?

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

以下是一个示例,展示了我的操作:

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表达式来实现同样的功能。


3
你可以用“经典”的开关替换它,不需要使用C#8的新功能特性。 - Gian Paolo
@GianPaolo,使用switch表达式比在case块中使用大量return或直接变量赋值的switch语句更加简洁和易于使用。 - Panagiotis Kanavos
2个回答

8

试试这个

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."
};

3

当然:

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."
};



网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接