如何复制 C# 3D 锯齿状数组

How to copy C# 3D jagged array

我需要(最初)复制一个 C# 3D 锯齿状数组,, to another 3D array (and eventually add x, y, z dimensions). I thought I could use the same syntax/logic to copy 就像我在下面所做的那样用于构建 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][];

为什么?

富 Class:

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;
    }