c#如何把某个长数组的一部分复制到另一个短数组里面

2025-02-27 09:21:11
推荐回答(2个)
回答1:

用Array.Copy方法将数组或者数组的一部分复制到另个数组。Array.Copy是静态方法,有多个重载版本。其中常用的是:

public static void Copy(
    Array sourceArray,
    int sourceIndex,
    Array destinationArray,
    int destinationIndex,
    int length);

各个参数含义如下

  • sourceArray —— 源数组

  • sourceIndex —— 表示 sourceArray 中复制开始处的索引

  • destinationArray —— 目标数组,它接收数据

  • destinationIndex —— 表示 destinationArray 中存储开始处的索引

  • length —— 要复制的元素数目。

用法举例如下:

(1)复制数组的一部分到另一个数组

int[] src = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
int[] dest = new int[4];
// 将数组 src 中元素 2,3,4,5 复制到 dest  
Array.Copy(src, 1, dest, 0, 4);

(2)复制整个数组

int[] src = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
int[] dest = new int[src.Length];
// 将数组 src 所有元素复制到 dest  
Array.Copy(src, 0, dest, 0, src.Length);

回答2:

不可能不用循环。

即使是 Array.CopyTo() 方法,本质也是循环,无非是你自己写循环还是 CLR 封装好了你调用。

况且 CopyTo 在目标数组长度小于原数组指定长度依旧会抛出异常。