加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:20:50 所属栏目:百科 来源:网络整理
导读:我知道这很可能是一个愚蠢的问题,但我是一名大学生,他是C#和面向对象编程的新手.我试图在别处找到答案,但我找不到任何有用的东西.调试器一直告诉我变量’cust_num在当前上下文中不存在’.如果有人能告诉我我做错了什么并让我觉得自己像个白痴,我会非常感激.
我知道这很可能是一个愚蠢的问题,但我是一名大学生,他是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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读