
..
。切片模式后面可以跟着另一个列表模式,比如 var 模式来捕获切片内容。[1, 2, .., 10]
:
int[] arr1 = { 1, 2, 10 };
int[] arr1 = { 1, 2, 5, 10 };
int[] arr1 = { 1, 2, 5, 6, 7, 8, 9, 10 };
public static int CheckSwitch(int[] values)
=> values switch
{
[1, 2, .., 10] => 1,
[1, 2] => 2,
[1, _] => 3,
[1, ..] => 4,
[..] => 50
};
WriteLine(CheckSwitch(new[] { 1, 2, 10 })); // prints 1
WriteLine(CheckSwitch(new[] { 1, 2, 7, 3, 3, 10 })); // prints 1
WriteLine(CheckSwitch(new[] { 1, 2 })); // prints 2
WriteLine(CheckSwitch(new[] { 1, 3 })); // prints 3
WriteLine(CheckSwitch(new[] { 1, 3, 5 })); // prints 4
WriteLine(CheckSwitch(new[] { 2, 5, 6, 7 })); // prints 50
public static string CaptureSlice(int[] values)
=> values switch
{
[1, .. var middle, _] => $"Middle {String.Join(", ", middle)}",
[.. var all] => $"All {String.Join(", ", all)}"
};
-
列表模式适用于任何可计数和可索引的类型 —— 这意味着它有一个可访问的
Length
或Count
属性,以及一个带int
或System.Index
形参的索引器。 -
切片模式适用于任何可计数和可切片的类型 —— 这意味着它有一个以
Range
为实参的可访问索引器,或者具有两个int
形参的可访问Slice
方法。 -
目前正在考虑在 IEnumerable 类型上添加对列表模式的支持,点此查看(
https://github.com/dotnet/csharplang/blob/main/proposals/list-patterns.md
)关于该列表模式的详细介绍。