【问题标题】:How to use C# pattern matching with tuples如何使用 C# 模式匹配与元组
【发布时间】:2020-08-25 15:24:29
【问题描述】:

我正在尝试使用 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# switch-statement c#-8.0


【解决方案1】:

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;
}

这里是demo


另一种编写代码的方法是使用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;
}

这里是demo


C# 9type 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,可以是enabled

【讨论】:

猜你喜欢
  • 2017-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-23
  • 2023-03-12
  • 2014-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多