在C#中,数组切片是一种从现有数组中获取子数组的方法。这在处理大型数组时非常有用,因为你可以只处理你关心的部分,而不是整个数组。
在C# 8.0及更高版本中,你可以使用范围运算符(..)来进行数组切片。这是一个例子:
int[] numbers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] slice = numbers[1..4]; // This will create an array with elements 1, 2, 3
在这个例子中,numbers[1..4]
创建了一个新的数组,其中包含numbers
数组中从索引1开始到索引4(不包括)的元素。
你也可以省略范围的开始或结束,这将默认为数组的开始或结束。例如:
int[] numbers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] startSlice = numbers[..4]; // This will create an array with elements 0, 1, 2, 3
int[] endSlice = numbers[6..]; // This will create an array with elements 6, 7, 8, 9
在这些例子中,numbers[..4]
创建了一个新的数组,其中包含numbers
数组中从开始到索引4(不包括)的元素,而numbers[6..]
创建了一个新的数组,其中包含numbers
数组中从索引6开始到结束的元素。
领取专属 10元无门槛券
手把手带您无忧上云