‘类、记录、结构或接口成员声明中存在无效标记“void”’错误及数组输出问题咨询
问题解答
1. 编译错误原因解析
你遇到的“类、记录、结构或接口成员声明中存在无效标记‘void’”错误,核心原因是代码里的Static拼写错误——C#的静态修饰符关键字是小写的static,大写的Static不是合法的修饰符。编译器无法识别这个错误的修饰符,就会把后续的void当成成员声明的一部分,而类成员声明不允许直接用void作为标记,因此抛出这个错误。
只需将Static改为小写的static,即可解决这个编译问题。
2. 数组输出不符合预期的解决办法
直接调用Console.WriteLine(twobyythree)输出二维数组时,默认会打印数组的类型名称(如System.Int32[,]),而非数组内容或维度信息。根据你的需求,分两种场景处理:
场景一:输出数组的维度(即[2,3])
通过GetLength()方法获取每个维度的长度,再拼接成目标格式:
using System; namespace namespaceaaa { class Anjila { static void Main(string[] args) { int[,] twobyythree = new int[2,3] {{1,2,3},{4,5,6}}; string dimensionStr = $"[{twobyythree.GetLength(0)},{twobyythree.GetLength(1)}]"; Console.WriteLine(dimensionStr); } } }
场景二:输出数组的所有元素(如[[1,2,3],[4,5,6]])
通过遍历数组的每个元素,拼接成嵌套数组的格式:
using System; namespace namespaceaaa { class Anjila { static void Main(string[] args) { int[,] twobyythree = new int[2,3] {{1,2,3},{4,5,6}}; string output = "["; // 遍历每一行 for (int i = 0; i < twobyythree.GetLength(0); i++) { output += "["; // 遍历当前行的每一列 for (int j = 0; j < twobyythree.GetLength(1); j++) { output += twobyythree[i, j]; if (j != twobyythree.GetLength(1) - 1) { output += ","; } } output += "]"; if (i != twobyythree.GetLength(0) - 1) { output += ","; } } output += "]"; Console.WriteLine(output); } } }
内容的提问来源于stack exchange,提问作者Angeela
相关产品推荐
相关产品推荐

