CSharp switch expression with or and default guard with condition

CSharp switch expression with or and default guard with condition

将 switch 表达式与 or 和带有条件的默认保护一起使用时,预期的行为是什么? 我希望任何符合 or 语句之一或默认守卫条件的东西都会进入这种情况,但显然这不是它的工作原理。

考虑以下示例

var types = new HashSet<string>();
types.Add("a");
types.Add("b");
types.Add("c");

var input = "d";
var result = input switch {
   "d" or _ when types.Contains(input) => "1",
   _ => "2",
};

        
Console.WriteLine(result); //I'd expect "1" but I get "2"

Documentation 状态:

The result of a switch expression is the value of the expression of the first switch expression arm whose pattern matches the input expression and whose case guard, if present, evaluates to true

你的表达式的第一臂违反了这一点,因为守卫存在,而守卫的计算结果为假。所以结果是第二个手臂(“2”)。