简体   繁体   English

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

[英]How to copy C# 3D jagged array

I need to (initially) copy a C# 3D jagged array, foos , to another 3D array (and eventually add x, y, z dimensions).我需要(最初)将 C# 3D 锯齿状数组foos 复制到另一个 3D 数组(并最终添加 x、y、z 维度)。 I thought I could use the same syntax/logic to copy foos as was used to build foos as I've done below (where row = 2, col = 3, z = 4):我想我可以使用与构建 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();
}

but I'm getting Index was outside the bounds of the array.但我得到的Index was outside the bounds of the array. on this line:在这一行:

newArray[row] = new Foo[foos[row].Length][];

Why?为什么?

Foo Class:福类:

public class Foo
{ 
    public string member;
}

Thanks.谢谢。

It doesn't look like your referenced array is being initialized properly.看起来您引用的数组没有正确初始化。 In order to set the value, your newArray must be initialized as the same size of your original.为了设置该值,您的 newArray 必须初始化为与原始大小相同的大小。

For this to work you'd need to pass in something like this:为此,您需要传入如下内容:

Foo[][][] firstFoo = new Foo[10][][];
Foo[][][] fooToCopy = new Foo[firstFoo.Length][][];

copyFooArray(firstFoo, ref fooToCopy);

Also, the ref keyword is unnecessary since arrays are passed by reference in c# anyways.此外,ref 关键字是不必要的,因为无论如何在 c# 中数组都是通过引用传递的。

In addition to the fix presented in the accepted answer, here's a faster way to do that:除了已接受的答案中提供的修复之外,还有一种更快的方法:

   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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM