如何在输入Y或y时重启C#脚本?遇CS1022错误求解决
问题分析与修复
你的代码存在编译错误和逻辑缺陷,以下是具体问题和修复方案:
编译错误原因
- 冗余嵌套大括号:
Main方法内部多了一对无意义的{},干扰编译器正常解析代码结构 - 无效的while条件:
while (value == "Y" || "y")语法错误,"y"是字符串类型,不能直接作为布尔表达式参与逻辑运算,必须完整写为value == "Y" || value == "y" - HTML转义引号:代码中的
"是HTML转义字符,C#编译器无法识别,需替换为标准双引号"
逻辑与健壮性问题
- 未处理非数字输入:
Convert.ToInt32(Console.ReadLine())在用户输入非数字时会直接抛出异常,导致程序崩溃 - 空输入未处理:用户直接按回车时,
Console.ReadLine()返回null,后续判断会触发空引用异常
修正后的代码
public class Program { public static void Main() { string value; do { int a1 = 0; // 确保第一个输入是有效数字 while (true) { Console.WriteLine("First value to add? : "); if (int.TryParse(Console.ReadLine(), out a1)) { break; } Console.WriteLine("Invalid input, please enter a valid number."); } int a2 = 0; // 确保第二个输入是有效数字 while (true) { Console.WriteLine("Second value to add? : "); if (int.TryParse(Console.ReadLine(), out a2)) { break; } Console.WriteLine("Invalid input, please enter a valid number."); } Console.WriteLine($"Sum result: {a1 + a2}"); Console.WriteLine("Type Y or y to restart the program."); // 处理空输入,避免空引用异常 value = Console.ReadLine()?.Trim() ?? string.Empty; } // 不区分大小写判断,简化逻辑 while (value.Equals("Y", StringComparison.OrdinalIgnoreCase)); } }
关键修复说明
- 移除
Main方法内冗余的嵌套大括号,规范代码结构 - 优化循环条件,使用
StringComparison.OrdinalIgnoreCase实现不区分大小写的输入判断,避免重复代码 - 用
int.TryParse替代Convert.ToInt32,处理非数字输入场景,提升程序健壮性 - 添加空输入处理逻辑,避免用户直接回车导致的空引用异常
内容的提问来源于stack exchange,提问作者GothenBurger
相关产品推荐
相关产品推荐

