C#编写Matrix类时如何初始化二维数组解决Invalid Rank Specifier报错
错误原因
你遇到的Invalid Rank Specifier错误是因为C#中两种二维数组的初始化语法存在差异:
int[][]是交错数组(锯齿数组):本质是「数组的数组」,外层数组的每个元素又是一个独立的一维数组,允许每行的长度不同,不能直接通过new int[m][n]一次性初始化。int[,]是矩形二维数组:是真正的连续内存存储的二维结构,所有行长度一致,更适合固定维度的矩阵场景。
方案1:继续使用交错数组int[][]
需要先初始化外层的行维度数组,再循环为每一行初始化列维度的数组:
class Matrix { //make the dimensions private private int m,n; //The Matrix constructor needs two parameters //The row and column dimensions //declare the two dimension array private int[][] array; public Matrix(int m, int n) { this.m = m; this.n = n; // 先初始化外层行数组 array = new int[m][]; // 逐行初始化列数组 for (int i = 0; i < m; i++) { array[i] = new int[n]; } } //method to allocate the Matrix }
后续赋值用法为array[行索引][列索引] = 数值。
方案2:改用矩形二维数组int[,](更推荐用于矩阵场景)
矩阵一般都是行列维度固定的矩形结构,用矩形二维数组初始化和访问都更简洁:
class Matrix { //make the dimensions private private int m,n; //The Matrix constructor needs two parameters //The row and column dimensions //declare the two dimension array private int[,] array; public Matrix(int m, int n) { this.m = m; this.n = n; // 直接一次性初始化即可,不会触发报错 array = new int[m, n]; } //method to allocate the Matrix }
后续赋值用法为array[行索引, 列索引] = 数值。
内容的提问来源于stack exchange,提问作者user16612111
相关产品推荐
相关产品推荐

