我试图找出如何用可能的普通数组来制作二维数组。下面是一个我怎么想象的例子:
int[,] original = new int[,] {{1,1,1,1}, {1,0,0,1}, {1,0,0,1}, {1,1,1,1}};
int[] part = {1,1,1,1};
int[,] copy = new int[,] {part}, {1,0,0,1}, {1,0,0,1}, {1,1,1,1}};发布于 2020-03-15 16:45:39
对于本机2d数组来说,这通常是不容易做到的,在初始化过程中也不可能做到。
但是,您可以使用以下扩展方法修改现有的2d数组。
static class Program
{
static void Main(string[] args)
{
int[,] original = new int[,] {
{ 1, 1, 1, 1 },
{ 1, 0, 0, 1 },
{ 1, 0, 0, 1 },
{ 1, 1, 1, 1 } };
int[] row_0 = original.GetRow(0);
// {1,1,1,1}
int[] part = { 1, 2, 3, 4 };
original.SetRow(0, part);
// {{1,2,3,4},{1,0,0,1},...}
}
public static T[] GetRow<T>(this T[,] matrix, int row)
{
int rows = matrix.GetLength(0);
int columns = matrix.GetLength(1);
T[] result = new T[columns];
if (row<=rows)
{
int size = Buffer.ByteLength(matrix)/rows;
Buffer.BlockCopy(matrix, row*size, result, 0, size);
}
return result;
}
public static void SetRow<T>(this T[,] matrix, int row, params T[] elements)
{
int rows = matrix.GetLength(0);
int columns = matrix.GetLength(1);
if (row<rows && elements.Length == columns)
{
int size = Buffer.ByteLength(elements);
Buffer.BlockCopy(elements, 0, matrix, row*size, size);
}
}
}当然,同样的功能对于参差不齐的数组来说也是微不足道的。使用int[,]代替int[][]。
static class Program
{
static void Main(string[] args)
{
int[][] original = new int[][] {
new int[] { 1, 1, 1, 1 },
new int[] { 1, 0, 0, 1 },
new int[] { 1, 0, 0, 1 },
new int[] { 1, 1, 1, 1 }
};
int[] row_0 = original[0];
// { 1, 1, 1, 1}
int[] parts = new[] { 1, 2, 3, 4 }; // implicit int[] type
original[0] = parts;
// { {1, 2, 3, 4}, {1, 0, 0, 1},..}
int[,] matrix = original.JaggedToMatrix();
}
public static T[,] JaggedToMatrix<T>(this T[][] jagged)
{
int rows = jagged.Length;
int columns = jagged.Length>0 ? jagged[0].Length : 0;
T[,] result = new T[rows, columns];
for (int i = 0; i < rows; i++)
{
result.SetRow(i, jagged[i]);
}
return result;
}
public static T[][] MatrixToJagged<T>(this T[,] matrix)
{
int rows = matrix.GetLength(0);
int columns = matrix.GetLength(1);
T[][] result = new T[rows][];
for (int i = 0; i < rows; i++)
{
result[i] = matrix.GetRow(i);
}
return result;
}
public static T[] GetRow<T>(this T[,] matrix, int row)
{
int rows = matrix.GetLength(0);
int columns = matrix.GetLength(1);
T[] result = new T[columns];
if (row<=rows)
{
int size = Buffer.ByteLength(matrix)/rows;
Buffer.BlockCopy(matrix, row*size, result, 0, size);
}
return result;
}
public static void SetRow<T>(this T[,] matrix, int row, params T[] elements)
{
int rows = matrix.GetLength(0);
int columns = matrix.GetLength(1);
if (row<rows && elements.Length == columns)
{
int size = Buffer.ByteLength(elements);
Buffer.BlockCopy(elements, 0, matrix, row*size, size);
}
}
}https://stackoverflow.com/questions/60694951
复制相似问题