在C#中,数组切片是从一个数组中提取连续元素的过程
- 使用LINQ扩展方法:
using System; using System.Linq; class Program { static void Main() { int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int startIndex = 2; int length = 5; var slicedArray = array.Skip(startIndex).Take(length).ToArray(); Console.WriteLine("原始数组: " + string.Join(", ", array)); Console.WriteLine("切片后的数组: " + string.Join(", ", slicedArray)); } }
- 使用ArraySegment
类:
using System; class Program { static void Main() { int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int startIndex = 2; int length = 5; var slicedArray = new ArraySegment(array, startIndex, length); Console.WriteLine("原始数组: " + string.Join(", ", array)); Console.WriteLine("切片后的数组: " + string.Join(", ", slicedArray)); } }
- 使用Span
类(C# 7.2及更高版本):
using System; class Program { static void Main() { int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int startIndex = 2; int length = 5; var slicedArray = new Span(array, startIndex, length); Console.WriteLine("原始数组: " + string.Join(", ", array)); Console.WriteLine("切片后的数组: " + string.Join(", ", slicedArray.ToArray())); } }
这些示例都可以实现数组切片。根据你的需求和项目的.NET版本,你可以选择最适合你的方法。