C#代码报错CS0650、CS0270:原因排查与修复方案咨询
C#编译错误CS0650与CS0270的成因及修复
错误信息
/home/runner/Relational-Operators/Operators/Logical.cs(23,42): error CS0650: Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. [/home/runner/Relational-Operators/main.csproj] /home/runner/Relational-Operators/Operators/Logical.cs(23,43): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) [/home/runner/Relational-Operators/main.csproj]
运行代码
using System; namespace Operators { class Logical { public static void Run() { Console.WriteLine("Enter two binary digits > "); int[] ints = new int[2]{Convert.ToInt32(Console.Read()), Convert.ToInt32(Console.Read())}; bool[] bools = new bool[2]; for (int i = 0; i < 2; i++) { switch (ints[i]) { case 0: bools[i] = false; break; case 1: bools[i] = true; break; default: throw new InvalidOperationException("Integer value is not valid"); } } bool b1, b2 = bools[0], bools[1]; if (b1 && b2) { Console.WriteLine("true"); } if (b1 || b2) { Console.WriteLine("true"); } else { Console.WriteLine("false"); } if (!(b1 && b2)) { Console.WriteLine("true"); } } } }
错误成因
两个错误都源于第23行的变量声明语法错误:
bool b1, b2 = bools[0], bools[1];
- CS0650:编译器误将
bools[1]解析为数组声明的一部分。C#中数组声明的语法是类型[] 变量名,你在变量声明列表中直接写数组索引表达式,导致编译器误解语法,认为你试图声明数组但写法不符合规范。 - CS0270:同样因上述语法错误,编译器认为你在变量声明中指定了数组大小,但C#不允许在变量声明时直接指定数组大小,必须通过
new关键字初始化数组。
此外,该行中b1未赋值,后续直接使用b1 && b2会触发未赋值局部变量的编译警告(或错误)。
修复方法
1. 修正变量声明与赋值
将错误的变量声明行改为正确的初始化方式:
// 方式1:一行完成声明与赋值 bool b1 = bools[0], b2 = bools[1]; // 方式2:分开声明更清晰 bool b1 = bools[0]; bool b2 = bools[1];
2. 修复输入读取的潜在问题
原代码中Console.Read()读取的是输入字符的ASCII值(比如输入'0'会得到48,而非数字0),会导致switch分支走到default抛出异常。可以通过以下方式修正:
// 方法1:减去字符'0'的ASCII值转换为数字 int[] ints = new int[2] { Convert.ToInt32(Console.Read()) - '0', Convert.ToInt32(Console.Read()) - '0' }; // 方法2:使用ReadLine读取整行输入并拆分(更可靠,避免读取换行符等问题) string input = Console.ReadLine().Trim(); int[] ints = new int[2] { int.Parse(input[0].ToString()), int.Parse(input[1].ToString()) };
内容的提问来源于stack exchange,提问作者Adonis
相关产品推荐
相关产品推荐

