And*_*rey 24 c# arrays multidimensional-array
这段代码工作正常:
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];
Run Code Online (Sandbox Code Playgroud)
但我没有太多运气用Array.Copy取代它.基本上,如果调整大小的数组较大,则只需在边缘添加空白矩形.如果它小,那么它应该切断边缘.
这样做时:
Array.Copy(tiles, newArray, newWidth * newHeight);
它弄乱了阵列,它的所有内容都变得混乱,并且不保留它们的原始索引.也许我只是有一个脑力计或其他什么?
jas*_*son 34
是.但是,它并不像您认为的那样有效.相反,它认为每个多维数组都是一维数组(实际上它们在内存中,它只是一个技巧,让我们在它们之上放置一些结构,将它们视为多维)然后复制单个 - 三维结构.所以,如果你有
1 2 3
4 5 6
Run Code Online (Sandbox Code Playgroud)
并希望将其复制到
x x x x
x x x x
Run Code Online (Sandbox Code Playgroud)
那么它会将第一个数组视为
1 2 3 4 5 6
Run Code Online (Sandbox Code Playgroud)
和第二个
x x x x x x x x
Run Code Online (Sandbox Code Playgroud)
结果将是
1 2 3 4 5 6 x x
Run Code Online (Sandbox Code Playgroud)
这对你来说就像
1 2 3 4
5 6 x x
Run Code Online (Sandbox Code Playgroud)
得到它了?
我用这个代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
像这样调用字符串数组
ResizeBidimArrayWithElements<string>(ref arrayOrigin, vNumRows, vNumCols);
Run Code Online (Sandbox Code Playgroud)