C#长数组的复制
时间: 2023-07-12 14:06:31 浏览: 47
在C#中,可以使用`Array.Copy()`方法来复制数组。该方法有三个参数:源数组、源数组的起始位置和目标数组的起始位置。以下是一个示例代码:
```
int[] sourceArray = { 1, 2, 3, 4, 5 };
int[] targetArray = new int[5];
Array.Copy(sourceArray, targetArray, sourceArray.Length);
```
在上面的代码中,我们将`sourceArray`中的所有元素复制到`targetArray`中。`sourceArray.Length`表示要复制的元素数量。
相关问题
C# 长字节数组的copy
在 C# 中,可以使用 `Array.Copy` 方法来复制一个字节数组。这个方法需要指定源数组、源数组的起始位置、目标数组、目标数组的起始位置以及要复制的字节数。下面是一个示例代码:
```csharp
byte[] source = new byte[] { 1, 2, 3, 4, 5 };
byte[] destination = new byte[5];
Array.Copy(source, 0, destination, 0, 5);
```
在上面的代码中,我们创建了一个长度为 5 的字节数组 `source`,并将其赋值为 `{ 1, 2, 3, 4, 5 }`。然后,我们创建了一个长度也为 5 的字节数组 `destination`,并调用了 `Array.Copy` 方法将 `source` 复制到 `destination` 中。在这个示例中,我们从 `source` 的索引 0 开始复制,复制 5 个字节到 `destination` 的索引 0 开始的位置。
如果需要复制的字节数不足 5 个,可以根据实际情况调整最后一个参数的值。同时,还需要确保目标数组的长度足够容纳复制的字节数,否则会抛出 `System.ArgumentException` 异常。
c# short数组转byte数组
可以使用以下代码将 short 数组转换为 byte 数组:
```csharp
short[] shortArray = { 1, 2, 3, 4, 5 };
byte[] byteArray = new byte[shortArray.Length * 2];
Buffer.BlockCopy(shortArray, 0, byteArray, 0, byteArray.Length);
```
这里使用了 `Buffer.BlockCopy` 方法,该方法可以将一个数组中的一段连续的元素复制到另一个数组中的一段连续的位置。在这个例子中,我们将 short 数组中的元素复制到 byte 数组中,每个 short 数字占用两个字节,因此需要将 byte 数组的长度设置为 short 数组长度的两倍。