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# 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,可以是enabled。