此开关和案例标签中括号的用途是什么?

Sur*_*ema 6 c# c#-8.0

我正在为项目服务编写一个函数,如果用户请求某个名称下的所有项目,它将全部返回。例如所有 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;
Run Code Online (Sandbox Code Playgroud)

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

它也是如何运作的?我不确定n是为了什么。

任何帮助是极大的赞赏!

进度:在跟进帮助程序后,我现在知道这{ }类似于var. 但我仍然不确定为什么只在这里使用它。

Ili*_*hev 7

这是一种能力的模式匹配的是年推出的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;
}
Run Code Online (Sandbox Code Playgroud)