C#中Try-Catch后Switch Case无法执行,提示变量未赋值求助
问题解决:choice未赋值的编译器错误
编译器提示choice是未赋值的局部变量,核心原因是C#的静态代码分析不会追踪循环的执行逻辑,它只识别代码路径的可能性——哪怕你的逻辑里循环会一直运行到用户输入有效数字,但编译器仍认为存在choice未被赋值就进入switch的潜在路径,因此抛出错误。
方法一:给choice赋初始值
直接在声明变量时赋予默认值,消除编译器的未赋值判断:
int choice = 0; // 赋予初始值 do { Console.Clear(); Console.WriteLine("1. Load Data"); Console.WriteLine("2. Add Customer"); Console.WriteLine("3. Sort Customers"); Console.WriteLine("4. Display Customers"); Console.WriteLine("5. Edit Customer"); Console.WriteLine("6. Exit\n"); Console.WriteLine("Chose an option 1-6: "); bool valid = true; do { try { choice = Convert.ToInt32(Console.ReadLine()); } catch (Exception) { valid = false; Console.WriteLine("please enter a number from 1 - 6"); } } while (valid == false); switch (choice) { case 1: break; case 2: break; case 3: break; case 4: break; case 5: break; default: break; } Console.Clear(); } while (choice != 6);
方法二:调整valid变量逻辑(更严谨)
将valid初始设为false,仅当用户输入有效时才标记为true,让编译器明确choice一定会在循环结束前被赋值:
int choice; do { Console.Clear(); Console.WriteLine("1. Load Data"); Console.WriteLine("2. Add Customer"); Console.WriteLine("3. Sort Customers"); Console.WriteLine("4. Display Customers"); Console.WriteLine("5. Edit Customer"); Console.WriteLine("6. Exit\n"); Console.WriteLine("Chose an option 1-6: "); bool valid = false; // 初始设为false do { try { choice = Convert.ToInt32(Console.ReadLine()); valid = true; // 输入有效时更新标记 } catch (Exception) { Console.WriteLine("please enter a number from 1 - 6"); } } while (!valid); // 直到输入有效才退出循环 switch (choice) { case 1: break; case 2: break; case 3: break; case 4: break; case 5: break; default: break; } Console.Clear(); } while (choice != 6);
额外优化:用TryParse替代异常捕获
异常处理开销较大,推荐使用int.TryParse来验证输入,代码更高效简洁:
int choice; do { Console.Clear(); Console.WriteLine("1. Load Data"); Console.WriteLine("2. Add Customer"); Console.WriteLine("3. Sort Customers"); Console.WriteLine("4. Display Customers"); Console.WriteLine("5. Edit Customer"); Console.WriteLine("6. Exit\n"); Console.WriteLine("Chose an option 1-6: "); bool valid = false; do { string input = Console.ReadLine(); if (int.TryParse(input, out choice)) { valid = true; } else { Console.WriteLine("please enter a number from 1 - 6"); } } while (!valid); switch (choice) { case 1: break; case 2: break; case 3: break; case 4: break; case 5: break; default: break; } Console.Clear(); } while (choice != 6);
内容的提问来源于stack exchange,提问作者noreon
相关产品推荐
相关产品推荐

