代码运行正常:
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);
它打乱了数组,数组的所有内容变得无序,并且不保留其原始索引。也许我脑子里放屁了还是怎么的?
是。然而,它并不像你想象的那样工作。相反,它将每个多维数组视为一个单维数组(实际上它们在内存中就是这样的,这只是一个技巧,让我们在它们上面放置一些结构,将它们视为多维数组),然后复制单维结构。所以如果你有
1 2 3
4 5 6
复制到
x x x x
x x x x
那么它会认为第一个数组是
1 2 3 4 5 6
,第二个为
x x x x x x x x
,结果将是
1 2 3 4 5 6 x x
显示为
1 2 3 4
5 6 x x
明白了吗?
我使用以下代码:
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);
简单使用"Clone()"函数,如下所示:
这是数组列表
object newArray = new object [row, column];
当您创建另一个数组时,只需使用以下代码:
object[,] clonedArray = (object[,]) newArray.Clone();
简单!玩得开心!
我需要在下一次中断发生之前从缓冲区中消费数据并将其复制到一个大型保存数组中。在循环中复制不是一种选择;太慢了。在完成所有复制之前,我不需要组合数据的多维结构,这意味着我可以将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