C# Array类的浅复制Clone()与Copy()的差别

1 Array.Clone方法

命名空间:System

程序集:mscorlib

语法:

public Object Clone()

Array的浅表副本仅复制Array的元素,不管他们是引用类型还是值类型。可是不负责这些引用所引用的对象。

新Array中的引用与原始Array的引用指向同样的对象。

例:

int[] intArray1 = {1, 2};

int [] intArray2 = (int [])intArray1.Clone();

这里须要说明的是。须要使用强制类型转换,原因在于Clone()返回的类型为Object

2 Array.Copy方法

命名空间:System

程序集:mscorlib

Copy有几个重载函数:

//从第一个元素開始复制Array中的一系列元素。将它们粘贴到还有一Array中(从第一个元素開始)。长度为32位整数

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

//从第一个元素開始复制Array中的一系列元素,将它们粘贴到还有一Array中(从第一个元素開始)。长度为64位整数

public static void Copy(Array sourceArray, Array destinationArray, long length)

//从指定的源索引開始,复制Array中的一系列元素。将它们粘贴到还有一Array中(从指定的目标索引開始)。长度和索引指定为32位整数

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

//从指定的源索引開始,复制Array中的一系列元素。将它们粘贴到还有一Array中(从指定的目标索引開始)。

长度和索引指定为64位整数

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

例: Array myIntArray=Array.CreateInstance( typeof(System.Int32), 5 );

for ( int i = myIntArray.GetLowerBound(0); i <= myIntArray.GetUpperBound(0); i++ )

{myIntArray.SetValue( i+1, i );}

Array myObjArray = Array.CreateInstance( typeof(System.Object), 5 );

for ( int i = myObjArray.GetLowerBound(0); i <= myObjArray.GetUpperBound(0); i++ )

{myObjArray.SetValue( i+26, i );}

// Copies the first element from the Int32 array to the Object array.

Array.Copy( myIntArray, myIntArray.GetLowerBound(0), myObjArray, myObjArray.GetLowerBound(0), 1 );

// Copies the last two elements from the Object array to the Int32 array.

Array.Copy( myObjArray, myObjArray.GetUpperBound(0) - 1, myIntArray, myIntArray.GetUpperBound(0) - 1, 2 );

差别:

Clone()返回值是Object,Copy返回值为void

Clone()是非静态方法。Copy为静态方法。

Clone()会创建一个新数组。Copy方法必须传递阶数同样且有足够元素的已有数组。

原文地址:https://www.cnblogs.com/wzzkaifa/p/6848957.html