下面的代码运行良好:
var newArray = new Rectangle[newHeight, newWidth];
for (int x = 0; x < newWidth; x++)
for (int y = 0; y < newHeight; y++)
newArray[y, x] = (x >= width) || (y >= height) ? Rectangle.Empty : tiles[y, x];
但我不太幸运地用Array.Copy取代了它。基本上,如果调整大小的数组更大,它只会将空白矩形添加到边缘。如果它是小的,那么它应该只切掉边缘。
执行此操作时:
Array.Copy(tiles, newArray, newWidth * newHeight);
它会弄乱数组,数组中的所有内容都会变得无序,并且不会保留它们的原始索引。也许我只是在胡思乱想什么的?
发布于 2011-09-01 02:37:40
是。然而,它并不像你想的那样工作。相反,它将每个多维数组视为一维数组(这实际上是它们在内存中的位置,这只是一个技巧,让我们将一些结构放在它们上面,将它们视为多维结构),然后复制一维结构。所以如果你有
1 2 3
4 5 6
并希望将其复制到
x x x x
x x x x
然后,它会将第一个数组视为
1 2 3 4 5 6
和第二个as
x x x x x x x x
结果将会是
1 2 3 4 5 6 x x
在您看来,它将显示为
1 2 3 4
5 6 x x
明白了?
发布于 2013-05-08 10:00:17
我使用以下代码:
public static void ResizeBidimArrayWithElements<T>(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<string>(ref arrayOrigin, vNumRows, vNumCols);
发布于 2015-10-09 05:19:19
在下一个中断命中之前,我需要消耗缓冲区中的数据并将其复制到一个大型保持数组中。在循环中复制不是一个选择;太慢了。在所有复制完成之前,我不需要组合数据的多维结构,这意味着我可以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
https://stackoverflow.com/questions/7265542
复制相似问题