C#中的每个变量都存在于由 花括号 定义的 范围内 : __
{ ... int x = 0; ... x = x + 1; // <- legal ... // <- x is defined up to here}x = x - 1; // <- illegal, providing there's no other "x" declared您的情况
cust_num受限制
while {...}。它必须考虑如果 cust_num_valid = true 并且根本没有cust_num ,那么代码应该返回什么值。
while (!cust_num_valid) { // <- Scope of cust_num begins cust_num_valid = true; Console.Write("Please enter customer number: "); string cust_num = Console.ReadLine(); if (cust_num == "000000" || !Regex.IsMatch(cust_num, @"^[0-9]+$") || cust_num.Length != 6) { cust_num_valid = false; Console.WriteLine("Invalid customer number detected. Customer numbers must be a 6 digit positive integer (zeros will not work)"); } } // <- Scope of cust_num ends return cust_num; // <- out of scope要修复您的代码放在
string cust_num = "";外面 的
while:
string cust_num = ""; // <- declaration while (!cust_num_valid) { cust_num_valid = true; Console.Write("Please enter customer number: "); cust_num = Console.ReadLine(); // <- no new declaration: "string" is removed if (cust_num == "000000" || !Regex.IsMatch(cust_num, @"^[0-9]+$") || cust_num.Length != 6) { cust_num_valid = false; Console.WriteLine("Invalid customer number detected. Customer numbers must be a 6 digit positive integer (zeros will not work)"); } } return cust_num;


