[英]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.