小编典典

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

c#

我知道这很可能是一个愚蠢的问题,但是我是一名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;
    }

阅读 344

收藏
2020-05-19

共1个答案

小编典典

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;
2020-05-19