如何解决多维数组引发的CS0022与CS1503编译错误?
解决C#多维数组与交错数组类型不兼容及索引访问错误
第一个错误:int[,] 无法转换为 int[][]
int[,] 是矩形多维数组,所有行的长度固定且相同;int[][] 是交错数组(数组的数组),每行可以是长度不同的独立数组。两者属于完全不同的类型,直接传参必然触发类型不匹配错误。你需要统一数组类型:要么把类的成员变量改成交错数组,要么把方法参数改成多维数组。
第二个错误:多维数组索引访问方式错误
当你把方法参数改为 int[,] 后,必须用 array[i, j] 的形式访问元素(逗号分隔两个索引),而不是 array[i][j](这是交错数组的专属访问方式)。此外你的代码还有两处逻辑问题:
- 循环条件错误:
array.GetLength(1)获取的是列数,遍历行应该用array.GetLength(0)(获取行数) - 索引越界:你的数组每行只有4个元素(索引范围0-3),
array[i][4]会访问不存在的第5个元素,需修正为合法索引
修正后的多维数组版本代码
using System; public class Program { public static void Main(string[] args){ testing Test = new testing(); if(Test.test(Test.array)){ Console.WriteLine("所有行符合条件"); } } } class testing{ // 保持多维数组定义不变 public int[,] array = {{10,0,25,7}, {5,0,30,10}}; // 方法参数改为与成员变量匹配的int[,] public bool test(int[,] array){ int count = 0; // 遍历所有行:GetLength(0)获取总行数 for (int i = 0; i < array.GetLength(0); i++){ // 多维数组用逗号分隔行列索引,此处检查每行第2列(索引1) if(array[i, 1] <= 0){ count++; } } // 判断是否所有行都满足条件 return count == array.GetLength(0); } }
若改用交错数组的版本代码
using System; public class Program { public static void Main(string[] args){ testing Test = new testing(); if(Test.test(Test.array)){ Console.WriteLine("所有行符合条件"); } } } class testing{ // 将成员变量改为交错数组 public int[][] array = new int[][] { new int[] {10,0,25,7}, new int[] {5,0,30,10} }; // 方法参数保持int[][]不变 public bool test(int[][] array){ int count = 0; // 交错数组用Length直接获取行数 for (int i = 0; i < array.Length; i++){ // 交错数组用双层索引访问元素 if(array[i][1] <= 0){ count++; } } return count == array.Length; } }
内容的提问来源于stack exchange,提问作者Shut_up_123
相关产品推荐
相关产品推荐

