C# 数组拷贝 数组截取前几个值 的方法

一、Array的ConstrainedCopy方法 msdn查看

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

使用它你可以在任意地方做拷贝

1、举例:

原数组

int[] a = new int[5] { 1, 3, 5, 4, 2 };

取前3位

int[] b = new int[3];//新数组
Array.ConstrainedCopy(a, 0, b, 0, 3);

//b现在存的就是 {1, 3, 5}

a就是原数组
第一个0就是原数组取值的起始位置
b就是目标数组
第二个0就是目标数组存值的起始位置
3就是存取的长度

二、Array的Resize方法(将一维数组的元素数更改为指定的新大小。)msdn查看

public static void Resize<T> (ref T[]? array, int newSize);
1、举例:

原数组

int[] a = new int[5] { 1, 3, 5, 4, 2 };

取前3位

Array.Resize(ref a, 3);

//a现在存的就是 {1, 3, 5}
原文地址:https://www.cnblogs.com/AlinaL/p/13716936.html