C# 当前上下文中不存在变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18233630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:35:52  来源:igfitidea点击:

Variable does not exist in the current context?

c#scopereturn

提问by SuperDicko

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!

我知道这很可能是一个愚蠢的问题,但我是一名刚接触 C# 和面向对象编程的大学生。我试图在别处找到答案,但我找不到任何可以提供帮助的东西。调试器不断告诉我变量“cust_num 在当前上下文中不存在”。如果有人能告诉我我做错了什么,让我觉得自己像个白痴,我将不胜感激。谢谢!

    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;
    }

采纳答案by Dmitry Bychenko

Each variable in C# exists within a scopewhich is defined by curly braces:

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

In your case, cust_numis restricted by while {...}. It has to think what value should your code return if cust_num_valid = trueand there's no cust_numat all.

在您的情况下,cust_numwhile {...}. 它必须考虑如果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

To repair your code put string cust_num = "";outsidethe while:

要修复放在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; 

回答by Mike Perrenoud

Define it outside the while:

在 之外定义它while

string cust_num = null;
while ...

and then inside the while set it like this:

然后在 while 中将其设置为:

cust_num = Console.ReadLine();

because you're trying to access it afterthe while:

因为您试图在一段时间访问它:

return cust_num;

回答by Artless

Your return cust_numstatement is outside of the definition context of cust_num. Since you defined it inside your whileloop, it exists only in that scope. You need to move it out of the loop.

您的return cust_num语句在 的定义上下文之外cust_num。由于您在while循环中定义了它,因此它仅存在于该范围内。您需要将其移出循环。

Any local variable you define exists only within the curly brackets that encapsulate it (and in any nested brackets).

您定义的任何局部变量仅存在于封装它的大括号内(以及任何嵌套的括号内)。

回答by DGibbs

You're trying to return cust_numoutside of the scope of the whileblock where it is defined. You need to define it outside of the while if you wish to return it, for example:

您试图返回定义它cust_numwhile块的范围之外。如果你想返回它,你需要在 while 之外定义它,例如:

string get_cust_num()
{
    bool cust_num_valid = false;
    string cust_num = string.Empty;
    while (!cust_num_valid)
    {
        cust_num_valid = true;
        Console.Write("Please enter customer number: ");
        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;
}

回答by HBennet

It appears that you are trying to return the value of cust_num. In order to return the value of cust_num, it needs to be declared outside of the while loop at the same level as where the "return" statement occurs.

看来您正在尝试返回 的值cust_num。为了返回 的值cust_num,它需要在与“return”语句发生位置相同的级别上在 while 循环之外声明。

See this link for more information: http://msdn.microsoft.com/en-us/library/ms973875.aspx

有关详细信息,请参阅此链接:http: //msdn.microsoft.com/en-us/library/ms973875.aspx

回答by Pierre-Luc Pineault

When a variable is defined in a code block, it is restrained to that scope (and of course starts at the variable declaration; you cannot use it before it is declared). If you look in your example, the variable is defined in the while block, but used outside of it.

当在代码块中定义变量时,它被限制在该范围内(当然从变量声明开始;在声明之前不能使用它)。如果您查看您的示例,该变量是在 while 块中定义的,但在其外部使用。

string get_cust_num()
{
    while ()
    {
        string cust_num = Console.ReadLine(); // cust_num scope starts here
        if ()
        {
        }
    } // cust_num scope ends here
    return cust_num;
}

You need to define it at the method level to use it :

您需要在方法级别定义它才能使用它:

string get_cust_num()
{
    string cust_num = Console.ReadLine(); // cust_num scope starts here

    while ()
    {
        if ()
        {
        }
    }

    return cust_num;
} // cust_num scope ends here