注解分析:
1,Array.Copy在CLR处理机制中最灵活,最强大,可装箱,拆箱复制,可加宽CLR基元类型,可内部判断实现了IFarmattable接口的兼容转换,当然这种强大方式必然会带来一定的性能损失。
2,Array.ConstrainedCopy 对复制要求严格,只能是同类型或者源数组类型是目标类型的派生元素类型,不执行装箱,拆箱,向下转换
3,Buffer.BlockCopy 则从本质上以字节为复制单位,这在底层语言C,C++的处理优势上,同理,效率之高可以理解。
当然如果对性能要求不高,Copy足矣,毕竟在上千次复制下,三者基本没消耗多少时间。使用时可根据项目需求斟酌选择!
问题:c#如何把某个长数组的一部分复制到另一个短数组里面
byte[] shortAry=new byte[4];
byte[] longAry=new byte[20];
如何把longAry[5,9(不含)]这4个字节复制到shortAry里面?
不要用循环。
用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);