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

c# – 当前上下文中不存在变量?,第1张

概述我知道这很可能是一个愚蠢的问题,但我是一名大学生,他是C#和面向对象编程的新手.我试图在别处找到答案,但我找不到任何有用的东西.调试器一直告诉我变量’cust_num在当前上下文中不存在’.如果有人能告诉我我做错了什么并让我觉得自己像个白痴,我会非常感激.谢谢! string get_cust_num() { bool cust_num_valid = false; 我知道这很可能是一个愚蠢的问题,但我是一名大学生,他是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;
总结

以上是内存溢出为你收集整理的c# – 当前上下文中不存在变量?全部内容,希望文章能够帮你解决c# – 当前上下文中不存在变量?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1240967.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存