【问题标题】:What is the purpose of the parenthesis in this switch and case label?这个 switch 和 case 标签中括号的目的是什么?
【发布时间】:2020-05-01 11:52:11
【问题描述】:

我正在为项目服务编写一个函数,如果用户请求某个名称下的所有项目,它将全部返回。比如所有 iPhone X 的手机等等。

我得到了帮助,使其中一个功能起作用,如果有超过 1 个项目,它将全部返回(这是第三种情况):

var itemsList = items.ToList();

switch (itemsList.Count())
{
    case 0:
        throw new Exception("No items with that model");

    case 1:
        return itemsList;

    case { } n when n > 1:
        return itemsList;
}

return null;

让我困惑的是{ } 是干什么用的?有人告诉我这是“一个用来说明类型的地方”,我不确定他们的意思。

它是如何工作的?我不确定n 的用途。

非常感谢任何帮助!

PROGRESS:在跟进 helper 之后,我现在知道 { }var 相似。但我仍然不确定为什么只在这里使用它。

【问题讨论】:

    标签: c# c#-8.0


    【解决方案1】:

    这是pattern matching 的一项功能,在C# 8 中引入。 { } 匹配任何非空值。 n 用于声明将保存匹配值的变量。这是来自MSDN 的示例,显示了{ } 的用法。

    您的样本说明:

    switch (itemsList.Count())
    {
        case 0:
            throw new Exception("No items with that model");
    
        case 1:
            return itemsList;
    
        // If itemsList.Count() != 0 && itemsList.Count() != 1 then it will
        // be checked against this case statement.
        // Because itemsList.Count() is a non-null value, then its value will
        // be assigned to n and then a condition agaist n will be checked.
        // If condition aginst n returns true, then this case statement is
        // considered satisfied and its body will be executed.
        case { } n when n > 1:
            return itemsList;
    }
    

    【讨论】:

      【解决方案2】:

      它被称为property pattern{} 处理剩余的 nonnull 对象。属性模式表示需要具有特定常量值的属性。但是,在您的示例中,我认为只是通过确保 n 不为空来在 switch 表达式中使用 n。我的意思是它的等价物如下。

      if (itemsList is {} n && n.Count() > 1)
      {
          return itemsList;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-17
        • 1970-01-01
        • 1970-01-01
        • 2018-05-05
        相关资源
        最近更新 更多