当前上下文中不存在变量? [英] Variable does not exist in the current context?
问题描述
我知道这很可能是一个愚蠢的问题,但我是一名刚接触 C# 和面向对象编程的大学生.我试图在别处找到答案,但我找不到任何可以提供帮助的东西.调试器不断告诉我变量cust_num 在当前上下文中不存在".如果有人能告诉我我做错了什么,让我觉得自己像个白痴,我将不胜感激.谢谢!
I know this is most likely a stupid question but I am a university student who is new to C# and object-oriented programming. I have tried to find the answer elsewhere but I wasn't able to find anything that could help. The debugger keeps telling me that the variable 'cust_num does not exist in the current context'. If someone can tell me what I have done wrong and make me feel like an idiot, I would greatly appreciate it. Thanks!
string get_cust_num()
{
bool cust_num_valid = false;
while (!cust_num_valid)
{
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)");
}
}
return cust_num;
}
推荐答案
C#中的每个变量都存在于范围内,该范围由花括号定义:
Each variable in C# exists within a scope which is defined by curly braces:
{
...
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.
In your case, cust_num
is restricted by while {...}
. It has to think what value should your code return if cust_num_valid = true and there's no
cust_num at all.
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 = "";
outside 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;
这篇关于当前上下文中不存在变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!