在C# 8中,
Type pattern
不支持匹配形式为
(decimal, decimal) t
的元组类型。但是我们可以通过指定类型
ValueTuple
来匹配元组类型,该类型用于表示
C#
中的元组。请注意保留HTML标签,此处无需解释。
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;
}
这里是演示。
另一种编写代码的方法是使用元组模式
:
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
对类型模式
进行了改进,使我们能够使用下一个语法(与您的原始代码示例相同)来匹配元组类型:
switch (aTuple)
{
case (decimal, decimal) t when t.Item1 == 0 || t.Item2 == 0:
return true;
}
这个功能在 C# 9 预览版
中,可以进行 启用。
LangVersion
的任何设置?元组模式是C# 8.0的一个新特性。 - Paulo Morgado