本章讲述:C# 数组复制
1、Buffer.BlockCopy(把某个数组的一部分复制到另一个数组中)
注解分析:
Buffer.BlockCopy 则从本质上以字节为复制单位,这在底层语言C,C++的处理优势上,同理,效率之高可以理解。
public static void BlockCopy (Array src,int srcOffset,Array dst,int dstOffset,int count)
src:源缓冲区;srcOffset:源目标开始复制的索引;dst:目标缓冲区; dstOffset:dst开始复制位置; count:要复制的字节数。
当然如果对性能要求不高,Copy足矣,毕竟在上千次复制下,三者基本没消耗多少时间。使用时可根据项目需求斟酌选择!
2、Array.Copy(把某个数组的一部分复制到另一个数组中 )
注解分析:
Array.Copy在CLR处理机制中最灵活,最强大,可装箱,拆箱复制,可加宽CLR基元类型,可内部判断实现了IFarmattable接口的兼容转换,当然这种强大方式必然会带来一定的性能损失。
public static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length);
各个参数含义如下:sourceArray —— 源数组;sourceIndex —— 表示 sourceArray 中复制开始处的索引;destinationArray —— 目标数组,它接收数据;
destinationIndex —— 表示 destinationArray 中存储开始处的索引;length —— 要复制的元素数目。
Array.Copy(array, copy, array.Length);
3、Array.ConstrainedCopy(把某个数组的一部分复制到另一个数组中 )
注解分析:
Array.ConstrainedCopy 对复制要求严格,只能是同类型或者源数组类型是目标类型的派生元素类型,不执行装箱,拆箱,向下转换
public static void ConstrainedCopy(Array sourceArray,int sourceIndex,Array destinationArray,int destinationIndex,int length)
4、引用复制,易引起错误,不推荐
int[] array = { 1, 5, 9, 3, 7, 2, 8 ,6, 4};
int[] copy = array;
5、遍历拷贝
int[] copy = new int[array .Length];
for (int i = 0; i < array.length; i++)
{
copy[i] = array[i];
}
6、CopyTo(将源数据拷贝到目标数组)
int[] copy = new int[array .Length];
array.CopyTo(copy, 0);
CopyTo方法用作将源数组全部拷贝到目标数组中,可以指定目标数组的起始索引,但需确保目标数组能容纳下源数组,CopyTo可用来合并多个数组
7、Clone(克隆,Clone的返回值类型是object)
int[] copy=(int[])array.Clone();
由于Clone的返回值类型是object,所以要强制转换为int[]
8、Marshal.copy();(效率最高)
Marshal.copy()方法用来在托管对象(数组)和非托管对象(IntPtr)之间进行内容的复制
示例:string name = "xuwei";
IntPtr pName = Marshal.AllocHGlobal(2*name.Length);
Marshal.Copy(name.ToCharArray(), 0, pName, name.Length);
char[] cName = new char[name.Length];
Marshal.Copy(pName, cName, 0, name.Length);
(1) 给pName指针分配了2*name.Length字节的空间
注意:Marshal.AllocHGlobal(Int32 cb)中的参数cb是分配的字节数
(2) 将name转换的char[]中的内容复制到pName所指的内存中,所取长度为char的个数,即name.Length
(3) 给cName分配name.Length个char位置
(4) 将pName中的内容复制到cName数组中,长度同样为name.Length