【问题标题】:CSharp switch expression with or and default guard with condition带有或的 CSharp 开关表达式和带有条件的默认保护
【发布时间】:2021-09-22 13:01:08
【问题描述】:

当使用带有 or 的 switch 表达式和带有条件的默认守卫时,预期的行为是什么? 我希望任何符合 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"

【问题讨论】:

    标签: c# .net switch-statement


    【解决方案1】:

    Documentation 状态:

    switch 表达式的结果是表达式的值 模式与输入匹配的第一个 switch 表达式 arm 表达式,其大小写保护(如果存在)评估为真

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

    【讨论】:

    • 是的,也来自文档:[the condition following the when] is an *additional* condition that must be satisfied *together* with a matched pattern(我的斜体)。
    • 如此有效地"d" or _ when types.Contains(input) 被评估为("d" or _) when types.Contains(input) 而不是"d" or (_ when types.Contains(input))。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 1970-01-01
    • 2020-12-08
    • 2013-10-22
    • 1970-01-01
    相关资源
    最近更新 更多