Array.Copy是否适用于多维数组?

这段代码工作正常:

var newArray = new Rectangle[newHeight, newWidth]; for (int x = 0; x < newWidth; x++) for (int y = 0; y = width) || (y >= height) ? Rectangle.Empty : tiles[y, x]; 

但我没有太多运气用Array.Copy取代它。 基本上,如果resize的数组较大,则只需在边缘添加空白矩形。 如果它小,那么它应该切断边缘。

这样做时:

Array.Copy(tiles, newArray, newWidth * newHeight);

它弄乱了arrays,它的所有内容都变得混乱,并且不保留它们的原始索引。 也许我只是有一个脑力计或其他什么?

是。 但是,它并不像您认为的那样有效。 相反,它认为每个多维数组都是一维数组(实际上它们在内存中,它只是一个技巧,让我们在它们之上放置一些结构,将它们视为多维)然后复制单个 – 三维结构。 所以,如果你有

 1 2 3 4 5 6 

并希望将其复制到

 xxxx xxxx 

然后它会将第一个数组视为

 1 2 3 4 5 6 

和第二个

 xxxxxxxx 

结果将是

 1 2 3 4 5 6 xx 

这对你来说就像

 1 2 3 4 5 6 xx 

得到它了?

我用这个代码:

 public static void ResizeBidimArrayWithElements(ref T[,] original, int rows, int cols) { T[,] newArray = new T[rows, cols]; int minX = Math.Min(original.GetLength(0), newArray.GetLength(0)); int minY = Math.Min(original.GetLength(1), newArray.GetLength(1)); for (int i = 0; i < minX; ++i) Array.Copy(original, i * original.GetLength(1), newArray, i * newArray.GetLength(1), minY); original = newArray; } 

像这样调用字符串数组

 ResizeBidimArrayWithElements(ref arrayOrigin, vNumRows, vNumCols); 

在下一次中断命中之前,我需要从缓冲区中使用数据并复制到大型保持数组。 在循环中复制不是一种选择; 太慢了。 在完成所有复制之前,我不需要组合数据的多维结构,这意味着我可以将Buffer.BlockCopy()转换为单维数组,然后再次复制到多维数组以获得所需的结构。 这里有一些代码(在控制台中运行),它将演示技术和性能。

 static class Program { [STAThread] static void Main() { Stopwatch watch = new Stopwatch(); const int width = 2; const int depth = 10 * 1000000; // Create a large array of data Random r = new Random(100); int[,] data = new int[width, depth]; for(int i = 0; i < width; i++) { for(int j = 0; j < depth; j++) { data[i, j] = r.Next(); } } // Block copy to a single dimension array watch.Start(); int[] buffer = new int[width * depth]; Buffer.BlockCopy(data, 0, buffer, 0, data.Length * sizeof(int)); watch.Stop(); Console.WriteLine("BlockCopy to flat array took {0}", watch.ElapsedMilliseconds); // Block copy to multidimensional array int[,] data2 = new int[width, depth]; watch.Start(); Buffer.BlockCopy(buffer, 0, data2, 0,buffer.Length * sizeof(int)); watch.Stop(); Console.WriteLine("BlockCopy to 2 dimensional array took {0}", watch.ElapsedMilliseconds); // Now try a loop based copy - eck! data2 = new int[width, depth]; watch.Start(); for (int i = 0; i < width; i++) { for (int j = 0; j < depth; j++) { data2[i, j] = data[i, j]; } } watch.Stop(); Console.WriteLine("Loop-copy to 2 dimensional array took {0} ms", watch.ElapsedMilliseconds); } } 

输出:

 BlockCopy to flat array took 14 ms BlockCopy to 2 dimensional array took 28 ms Loop-copy to 2 dimensional array took 149 ms 

简单地使用“Clone()”函数,如下所示:

这是你的数组列表

 object newArray = new object [row, column]; 

在创建另一个Array时,只需使用以下代码:

 object[,] clonedArray = (object[,]) newArray.Clone(); 

简单! 玩得开心!