[英]How to copy C# 3D jagged array
我需要(最初)将 C# 3D 锯齿状数组foos 复制到另一个 3D 数组(并最终添加 x、y、z 维度)。 我想我可以使用与构建 foos 相同的语法/逻辑来复制foos ,就像我在下面所做的那样(其中 row = 2, col = 3, z = 4):
private static void copyFooArray(Foo[][][] foos, ref Foo[][][] newArray)
{
for (int row = 0; row < foos.Length; row++)
{
newArray[row] = new Foo[foos[row].Length][];
for (int col = 0; col < foos[row].Length; col++)
{
newArray[row][col] = new Foo[foos[row][col].Length];
for (int z= 0; z< foos[row][col].Length; z++)
{
newArray[row][col][z] = new Foo();
newArray[row][col][z].member = foos[row][col][z].member;
}
}
}
Console.Read();
}
但我得到的Index was outside the bounds of the array.
在这一行:
newArray[row] = new Foo[foos[row].Length][];
为什么?
福类:
public class Foo
{
public string member;
}
谢谢。
看起来您引用的数组没有正确初始化。 为了设置该值,您的 newArray 必须初始化为与原始大小相同的大小。
为此,您需要传入如下内容:
Foo[][][] firstFoo = new Foo[10][][];
Foo[][][] fooToCopy = new Foo[firstFoo.Length][][];
copyFooArray(firstFoo, ref fooToCopy);
此外,ref 关键字是不必要的,因为无论如何在 c# 中数组都是通过引用传递的。
除了已接受的答案中提供的修复之外,还有一种更快的方法:
public static int[][][] Copy(int[][][] source)
{
int[][][] dest = new int[source.Length][][];
for (int x = 0; x < source.Length; x++)
{
int[][] s = new int[source[x].Length][];
for (int y = 0; y < source[x].Length; y++)
{
int[] n = new int[source[x][y].Length];
int length = source[x][y].Length * sizeof(int);
Buffer.BlockCopy(source[x][y], 0, n, 0, length);
s[y] = n;
}
dest[x] = s;
}
return dest;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.