Collection < T > .CopyTo(T [],Int32)方法用于从目标数组的指定索引处开始,将整个Collection < T>复制到兼容的一维数组。
句法:
public void CopyTo (T[] array, int index);
参数:
array : The one-dimensional Array that is the destination of the elements copied from Collection<T>. The Array must have zero-based indexing.
index : The zero-based index in array at which copying begins.
例外情况:
- ArgumentNullException:如果数组为null。
- ArgumentOutOfRangeException:如果索引小于零。
- ArgumentException:如果源Collection < T >中的元素数大于从索引到目标数组末尾的可用空间。
下面给出了一些示例,以更好地理解实现:
范例1:
// C# code to copy the entire Collection
// to a compatible one-dimensional Array,
// starting at the specified index of
// the target array
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
class GFG {
// Driver code
public static void Main()
{
// Creating a collection of strings
Collection myColl = new Collection();
myColl.Add("A");
myColl.Add("B");
myColl.Add("C");
myColl.Add("D");
myColl.Add("E");
// Creating a string array
string[] myArr = new string[myColl.Count];
// Copying the entire Collection to a
// compatible one-dimensional Array,
// starting at the specified index
// of the target array
myColl.CopyTo(myArr, 0);
// Displaying the elements in myArr
foreach(string str in myArr)
{
Console.WriteLine(str);
}
}
}
输出:
A
B
C
D
E
范例2:
// C# code to copy the entire Collection
// to a compatible one-dimensional Array,
// starting at the specified index of
// the target array
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
class GFG {
// Driver code
public static void Main()
{
// Creating a collection of ints
Collection myColl = new Collection();
myColl.Add(2);
myColl.Add(3);
myColl.Add(4);
myColl.Add(5);
// Creating an integer array
int[] myArr = new int[myColl.Count];
// Copying the entire Collection to a
// compatible one-dimensional Array,
// starting at the specified index
// of the target array
// This should raise "ArgumentOutOfRangeException"
// as index is less than 0
myColl.CopyTo(myArr, -5);
// Displaying the elements in myArr
foreach(int i in myArr)
{
Console.WriteLine(i);
}
}
}
运行时错误:
Unhandled Exception:
System.ArgumentOutOfRangeException: Value has to be >= 0.
Parameter name: destinationIndex
笔记:
- 此方法使用Array.Copy复制元素。
- 将元素以枚举器遍历Collection < T >的相同顺序复制到Array。
- 此方法是O(n)运算,其中n是Count。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.objectmodel.collection-1.copyto?view=netframework-4.7.2