C#中如何访问switch语句内定义的变量?
问题背景
跟随Brackeys教程初学C#,开发简易数学答题测验程序时,无法跨代码块引用答题结果变量correct01、correct02实现累计得分计算,VS Code提示switch语句内声明的同名变量未被使用,尝试删除冲突变量实例后仍未找到适配当前开发场景的解决方案。
错误原因
- C#遵循块级作用域规则:在switch的case代码块内写
bool correct01 = true时,本质是在case的局部作用域内新建了一个和外部同名的全新变量,和switch外提前声明的correct01完全无关,外部代码读不到这个局部变量的值,所以会提示变量未使用、外部引用拿不到正确结果 - 第二题的switch判断对象写错:需要判断第二题答案
ans02是否等于100,原代码误写成判断ans01,直接导致第二题判分逻辑完全失效 - 第三题的判分逻辑顺序错误:先判断
correct01 == true || correct02 == true的话,哪怕两个题都答对,也会先命中这个条件,永远触发不了满分3/3的提示
修复方法
不需要额外引入复杂语法,只需要做3处核心调整:
- switch的case块内不要重新声明
bool类型的同名变量,直接给外部提前定义好的correct01、correct02赋值即可 - 把第二题switch的判断参数从
ans01改成ans02 - 调整第三题的判分顺序,优先判断两题全对的满分场景,再判断单题答对的场景
修复后的完整代码
using System; namespace Learning_C_ { class Program { static void Main(string[] args) { Console.WriteLine("Are you ready to solve some math equations?"); if (Console.ReadLine() == "Yes") { Console.WriteLine("Definitely Generating Math Equations"); } else { Console.WriteLine("Well thats too bad... You have to do it anyways"); } Console.Write("Solve for x\n5x + 5 = 25\nx = "); int ans01 = Convert.ToInt32(Console.ReadLine()); bool correct01 = false; switch (ans01) { case 4: // 直接给外部变量赋值,不要重新声明新变量 correct01 = true; Console.WriteLine("Wow, you got it correct!\nThat's 1/3"); break; default: correct01 = false; Console.WriteLine("Oops! You got that one incorrect...\n0/3"); break; } Console.Write("Solve\n75 + 2 * 12.5 = "); int ans02 = Convert.ToInt32(Console.ReadLine()); bool correct02 = false; // 修正:判断ans02而不是ans01 switch (ans02){ case 100: // 直接给外部变量赋值,不要重新声明新变量 correct02 = true; if(correct01 == true){ Console.WriteLine("Wow, you got it correct!\nThat's 2/3"); } else { Console.WriteLine("Wow, you got it correct!\nThat's 1/3"); } break; default: correct02 = false; if (correct01 == true) { Console.WriteLine("Oops! You got that one incorrect...\n1/3"); } else { Console.WriteLine("Oops! You got that one incorrect...\n0/3"); } break; } Console.Write("Simplify\n5(4n + 3) = 23\nAnswer: "); string ans03 = Convert.ToString(Console.ReadLine()); // 用单独变量累计总分,减少重复判断 int totalScore = 0; if (correct01) totalScore++; if (correct02) totalScore++; switch (ans03){ case "n = 0.4": totalScore++; if(totalScore == 3){ Console.WriteLine("Wow, you got it correct!\nThat's 3/3, congrats! You aced this test!"); } else { Console.WriteLine($"Wow, you got it correct!\nThat's {totalScore}/3"); } break; default: Console.WriteLine($"Oops! You got that one incorrect...\n{totalScore}/3"); break; } Console.ReadKey(); } } }
额外说明:
- 原代码第三题的数学计算结果有误:
5(4n + 3) = 23计算后n=0.4,如果要让正确答案为n=1,需要把题目等式调整为比如5(4n - 3) = 5- 新增
totalScore变量统一累计答对题数,不用反复写多分支判断两个布尔值的组合,代码更简洁不容易出逻辑错误
内容的提问来源于stack exchange,提问作者blank blanks
相关产品推荐
相关产品推荐

