在C#中,数组切片是从一个数组中提取连续元素的过程
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));
}
}
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<int>(array, startIndex, length);
Console.WriteLine("原始数组: " + string.Join(", ", array));
Console.WriteLine("切片后的数组: " + string.Join(", ", slicedArray));
}
}
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<int>(array, startIndex, length);
Console.WriteLine("原始数组: " + string.Join(", ", array));
Console.WriteLine("切片后的数组: " + string.Join(", ", slicedArray.ToArray()));
}
}
这些示例都可以实现数组切片。根据你的需求和项目的.NET版本,你可以选择最适合你的方法。