web-dev-qa-db-ja.com

このスイッチとケースラベルの括弧の目的は何ですか?

ユーザーが特定の名前ですべてのアイテムを要求した場合にすべてを返すアイテムサービスの関数を書いています。 iPhone Xなどのすべての電話など.

1つ以上のアイテムがある場合、それらがすべてを返す関数の1つを機能させるために助けを得ました(これは3番目のケースです)。

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の意味がわかりません。

どんな助けでも大歓迎です!

進捗状況:ヘルパーにフォローアップしたところ、{ }varに似ています。しかし、それがここでのみ使用される理由はまだわかりません。

6
Suraj Cheema

C# 8で導入されたのは パターンマッチング の機能です。 { }は、null以外の値と一致します。 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;
}
7
Iliar Turdushev

property pattern{}は、残りのnonnullオブジェクトを扱います。プロパティパターンは、特定の定数値を必要とするプロパティを表します。しかし、あなたの例では、nがnullでないことを保証することにより、スイッチ式でnを使用するだけだと思います。つまり、以下のようになります。

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