簡體   English   中英

如何使用 C# 模式匹配元組

[英]How to use C# pattern matching with tuples

我正在試驗 switch 語句模式匹配,並且我正在尋找一種方法,如果兩個值元組中的任何一個值為零,則返回 false。 這是我正在嘗試的代碼:

static bool IsAnyValueZero((decimal, decimal) aTuple)
{
    switch(aTuple)
    {
        case (decimal, decimal) t when t.Item1 == 0 || t.Item2 == 0:
            return true;
    }
    return false;
}

在 VSCode 1.47 和 dotnetcore 3.14 中,我收到一個編譯時錯誤:

CS8652:功能“類型模式”在預覽中

編寫此代碼的最佳兼容方式是什么?

C# 8中的Type pattern不支持匹配(decimal, decimal) t形式的元組類型。 但是我們可以通過在C#指定用於表示元組的類型ValueTuple來匹配元組類型:

public static bool IsAnyValueZero((decimal, decimal) aTuple)
{
    switch (aTuple)
    {
        case ValueTuple<decimal, decimal> t when t.Item1 == 0 || t.Item2 == 0:
            return true;
    }
    return false;
}

這是演示


另一種編寫代碼的方法是使用tuple pattern

public static bool IsAnyValueZero((decimal, decimal) aTuple)
{
    switch (aTuple)
    {
        case (decimal i1, decimal i2) when i1 == 0 || i2 == 0:
            return true;
    }
    return false;
}

或者我們可以用下一種方式重寫這段代碼:

public static bool IsAnyValueZero((decimal, decimal) aTuple)
{
    switch (aTuple)
    {
        // Discards (underscores) are required in C# 8. In C# 9 we will
        // be able to write this case without discards.
        // See https://github.com/dotnet/csharplang/blob/master/proposals/csharp-9.0/patterns3.md#type-patterns.
        case (decimal _, decimal _) t when t.Item1 == 0 || t.Item2 == 0:
            return true;
    }
    return false;
}

我們也可以明確指定匹配值:

public static bool IsAnyValueZero((decimal, decimal) aTuple)
{
    switch (aTuple)
    {
        case (0, _):
            return true;
        case (_, 0):
            return true;
    }
    return false;
}

這是演示


C# 9添加了對type pattern改進,以便我們能夠使用下一個語法(如您的原始代碼示例中所示)匹配元組類型:

switch (aTuple)
{
    // In C# 9 discards (underscores) are not required.
    case (decimal, decimal) t when t.Item1 == 0 || t.Item2 == 0:
        return true;
}

此功能在C# 9 preview ,可以啟用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM