Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/silverlight/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用元组的C#模式匹配_C#_Switch Statement_C# 8.0 - Fatal编程技术网

如何使用元组的C#模式匹配

如何使用元组的C#模式匹配,c#,switch-statement,c#-8.0,C#,Switch Statement,C# 8.0,我正在试验switch语句模式匹配,我正在寻找一种方法,如果两值元组中的任一值为零,则返回false。这是我正在尝试的代码: static bool IsAnyValueZero((十进制,十进制)整数) { 开关(aTuple) { 当t.Item1==0 | | t.Item2==0时的大小写(十进制,十进制): 返回true; } 返回false; } 在VSCode 1.47和dotnetcore 3.14中,我得到一个编译时错误: CS8652:功能“类型模式”正在预览中` 编写此代

我正在试验switch语句模式匹配,我正在寻找一种方法,如果两值元组中的任一值为零,则返回false。这是我正在尝试的代码:

static bool IsAnyValueZero((十进制,十进制)整数)
{
开关(aTuple)
{
当t.Item1==0 | | t.Item2==0时的大小写(十进制,十进制):
返回true;
}
返回false;
}
在VSCode 1.47和dotnetcore 3.14中,我得到一个编译时错误:

CS8652:功能“类型模式”正在预览中`


编写此代码的最佳兼容方式是什么?
C#8
中的
类型模式
不支持与
(十进制,十进制)t
格式中的元组类型进行匹配。但是我们可以通过指定用于在
C#
中表示元组的类型来匹配元组类型:

或者我们可以用下一种方法重写此代码:

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
添加了改进,以便我们能够使用下一个语法(如原始代码示例中的语法)匹配元组类型:


此功能位于
C#9预览中,并且可以是。

您的csproj上是否有任何设置覆盖
LangVersion
?是一项功能。@PauloMorgado不感谢你。但我还是感到困惑,因为我认为我是在用C#7.0的特性来完成这篇文章。哪里出了问题?
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;
}
switch (aTuple)
{
    // In C# 9 discards (underscores) are not required.
    case (decimal, decimal) t when t.Item1 == 0 || t.Item2 == 0:
        return true;
}