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

前端之家收集整理的这篇文章主要介绍了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;
    }

解决方法

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受到{…}的限制.如果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

修复你的代码put string cust_num =“”;在外面:

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;
原文链接:https://www.f2er.com/csharp/98251.html

猜你在找的C#相关文章