在 C# switch 表达式中使用块?

Using blocks in C# switch expression?

我找不到解决此问题的文档。 (也许我只是不擅长使用 google...) 我的猜测是答案是否定的,但是我不明白文档中在哪里解决了这个问题。 准确地说,我的问题如下。

假设,我想执行这样的操作:

DirectoryInfo someDir = new DirectoryInfo(@".\someDir");
Console.WriteLine($"Would you like to delete the directory {someDir.FullName}?");
string response = Console.ReadLine().ToLower();

response switch
{
    "yes" => { someDir.Delete(); ... MoreActions},
     _ => DoNothing()
};

我知道我可以通过使用常规 switch 或 if/else 来实现所需的行为,但是我很好奇在这种情况下是否可以使用 switch 表达式。

however I didn't understand where this is addressed in the documentation

这个说的很清楚了here:

There are several syntax improvements here:

  • The variable comes before the switch keyword. The different order makes it visually easy to distinguish the switch expression from the switch statement.
  • The case and : elements are replaced with =>. It's more concise and intuitive.
  • The default case is replaced with a _ discard.
  • The bodies are expressions, not statements.

{ someDir.Delete(); ... MoreActions} 不是表达式。

但是,您可以滥用每个功能,正如他们所说:)

可以 使 switch 表达式的计算结果为 Action,并调用该操作:

Action a = response switch
{
    "yes" => () => { ... },
     _ => () => { .... }
};
a();

您甚至可以将其简化为一条语句:

(response switch
{
    "yes" => (Action)(() => { ... }),
     _ => () => { ... }
})();

但不要这样做...

As per documentation: 正文是表达式,不是语句。

不过你可以这样做:

Action fn = response switch
{
    "yes" => () => { BlockTest(); },
     _ => () => { OldTest(); }
};

您还可以引入 local function(C# 7.0 及更高版本)并执行以下操作:

response switch
{
    "yes" => DoSomething(),
     _ => DoNothing()
};

void DoSomething()
{
    someDir.Delete();
    ... MoreActions
}

我想这个功能很快就会出现。 Proposal for this