C# 数组 - CopyTo() 方法
C# 数组 CopyTo() 方法将当前一维数组的所有元素复制到另一个一维数组,从目标数组中指定的索引开始。
根据重载的 CopyTo 方法,整数位会有所不同;您可以传递 32 位整数索引或 64 位整数索引。
异常
CopyTo() 方法存在以下异常 -
- ArgumentNullException:如果目标数组为空,则抛出此异常。
- ArgumentOutOfRangeException:如果索引小于零,则抛出此异常。
- ArgumentException:如果目标数组没有足够的空间容纳复制的元素或类型不兼容,则抛出此异常。
语法
以下是 C# 数组 CopyTo() 方法的语法 -
public void CopyTo(Array array, int index);
参数
此方法接受以下参数 -
- array:元素将被复制到的目标数组。
- index:复制开始位置在目标数组中的索引值。
返回值
此方法不返回任何值。
示例 1:复制整数数组
这是 CopyTo() 方法的基本示例,这里我们复制一个整数数组 -
using System;
class Program {
static void Main() {
int[] source = { 1, 2, 3, 4, 5 };
int[] destination = new int[10];
source.CopyTo(destination, 2);
Console.WriteLine(string.Join(", ", destination));
}
}
输出
以下是输出 -
0, 0, 1, 2, 3, 4, 5, 0, 0, 0
示例 2:将字符串复制到另一个数组
让我们看另一个 CopyTo() 方法的示例。在这里,我们将一个字符串数组复制到另一个起始索引为 3 的数组中 -
using System;
class Program {
static void Main() {
string[] source = { "apple", "banana", "cherry" };
string[] destination = new string[5];
source.CopyTo(destination, 1);
Console.WriteLine(string.Join(", ", destination));
}
}
输出
以下是输出 -
, apple, banana, cherry,
示例 3:将字符复制到另一个数组
在前面的示例中,我们复制了整数和字符串数组,这里我们使用 CopyTo() 方法复制字符数组 -
using System;
class Program {
static void Main() {
char[] source = { 'A', 'B', 'C' };
char[] destination = new char[6];
source.CopyTo(destination, 3);
Console.WriteLine(string.Join(", ", destination));
}
}
输出
以下是输出 -
., ., ., A, B, C
示例 4:处理异常
这是 CopyTo() 方法的另一个示例。在这里,我们处理异常并显示异常 -
using System;
class Program {
static void Main() {
try {
int[] source = { 1, 2, 3 };
int[] destination = new int[2];
source.CopyTo(destination, 0);
}
catch (Exception ex) {
Console.WriteLine($"Exception: {ex.Message}");
}
}
}
输出
以下是输出 -
Exception: Destination array was not long enough. Check destIndex and length, and the array's lower bounds Parameter name: destinationArray

csharp_array_class.html