【总结】Array获取子数组
0.扩展方法如下/// <summary>
/// 从此实例检索子数组
/// </summary>
/// <param name="source">要检索的数组</param>
/// <param name="startIndex">起始索引号</param>
/// <param name="length">检索最大长度</param>
/// <returns>与此实例中在 startIndex 处开头、长度为 length 的子数组等效的一个数组</returns>
public static Array SubArray(this Array source, Int32 startIndex, Int32 length)
{
if (startIndex < 0 || startIndex > source.Length || length < 0)
{
throw new ArgumentOutOfRangeException();
}
Array Destination;
if (startIndex + length <= source.Length)
{
Destination = Array.CreateInstance(source.GetValue(0).GetType(), length);
Array.Copy(source, startIndex, Destination, 0, length);
}
else
{
Destination = Array.CreateInstance(source.GetValue(0).GetType(), source.Length - startIndex);
Array.Copy(source, startIndex, Destination, 0, source.Length - startIndex);
}
return Destination;
}
1. 调用示例如下
byte[] src = { 1, 2, 3, 4, 5, 6, 7, 8 };
byte[] des = (byte[])src.SubArray(2, 3);
foreach (var data in des)
{
Console.WriteLine(data.ToString());
}
2. 输出结果
{:5_124:}预备学c#,先收藏以后可
页:
[1]