【问题标题】:C# switch expression / pattern matching - when clause inside orC# switch 表达式/模式匹配 - when 子句里面 or
【发布时间】:2021-11-17 08:50:11
【问题描述】:

考虑以下几点:

var ch = 'i';
var str = "some item";

var result = ch switch
            {
                'a' => DoA("some", "parameters"),
                _ when str.Contains("action a") => DoA("some", "parameters"),
                'b' => DoB("some", "parameters"),
                _ when str.Contains("action b") => DoB("some", "parameters"),
                'c' => DoC(),
                _ when str.Contains("action c") => DoC("some", "parameters"),
                _ => new Exception("")
            };

现在您可以在调用方法时看到重复,所以理想情况下我想要这样的东西:

var result = ch switch
            {
                'a' or (_ when str.Contains("action a")) => DoA("some", "parameters"),
                'b' or (_ when str.Contains("action b")) => DoB("some", "parameters"),
                'c' or (_ when str.Contains("action c")) => DoC("some", "parameters"),
                _ => new Exception("")
            };

但这会给我一个语法错误。
删除括号确实可以编译,但是逻辑等效于
('a' or _) when str.Contains("action a")) => DoA("some", "parameters") 这不是我想要的。

有没有办法做到不重复?

【问题讨论】:

  • 没有。当when 子句出现在模式之后,并且您试图将其折叠到模式本身中时

标签: c# pattern-matching c#-10.0


【解决方案1】:

你可以使用

var result = ch switch
{
   _ when ch == 'a' || str.Contains("action a") => ...

注意:我个人不喜欢这种类型的 switch 表达式,它看起来有点笨拙和丑陋

或者另一种选择是用老式的方式创建一个方法¯\_(ツ)_/¯

public Bob DoSomething(char ch)
{
   if(ch =='a' || str.Contains("action a"))
       return DoA("some", "parameters");
   ...

【讨论】:

    猜你喜欢
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    相关资源
    最近更新 更多