【问题标题】:How to resolve "The name *** does not exist in the current context" error?如何解决“当前上下文中不存在名称***”错误?
【发布时间】:2019-03-12 17:14:46
【问题描述】:

我正在尝试向此代码添加一个 Try/Catch 块,但我不知道要更改什么才能使其正常工作..

有什么建议吗? 收到此错误:

“错误 CS0103 名称‘华氏’在当前上下文中不存在”

class Program
{
    static int FahrenheitToCelsius(int fahrenheit)
    {
        int celsius = ((fahrenheit - 32) * 5) / 9;
        return celsius;
    }

    static void Main(string[] args)
    {
        int celsius;

        Console.WriteLine("Hello! Welcome to the sauna!");
        Console.WriteLine();
        Console.WriteLine("Please enter your desired degrees in Fahrenheit: ");

        do
        {
            try
            {
                int fahrenheit = Convert.ToInt32(Console.ReadLine());
            }
            catch (FormatException)
            {
            }

            celsius = FahrenheitToCelsius(fahrenheit);
            Console.WriteLine("The sauna is now set to " + fahrenheit + 
                " degrees Fahrenheit, which equals to " + celsius + " degrees Celsius.");

            if (celsius < 25)
            {
                Console.WriteLine("Way too cold! Turn the heat up: ");
            }
            else if (celsius < 50)
            {
                Console.WriteLine("Too cold, turn the heat up: ");
            }
            else if (celsius < 73)
            {
                Console.WriteLine("Just a little bit too cold, turn the heat up a " + 
                    "little to reach the optimal temperature: ");
            }
            else if (celsius == 75)
            {
                Console.WriteLine("The optimal temperature has been reached!");
            }
            else if (celsius > 77)
            {
                Console.WriteLine("Too hot! Turn the heat down: ");
            }
            else
                Console.WriteLine("The sauna is ready!");
            {
            }
        } while (celsius < 73 || 77 < celsius);

        Console.ReadLine();
    }
}

【问题讨论】:

  • 如果您想在该块之外访问它,只需在farenheit 块的范围之外定义farenheit。也许你在哪里定义celcius
  • 话虽如此,您应该真正使用int.TryParse 而不是异常处理来验证用户输入。

标签: c# try-catch


【解决方案1】:

看看这段代码:

try
{
    int fahrenheit = Convert.ToInt32(Console.ReadLine());
}

fahrenheit 将仅存在于 try {} 块内,而您稍后尝试使用它。将其移至父范围:

int fahrenheit;
while (true)
{
   try
   {
        fahrenheit = Convert.ToInt32(Console.ReadLine());
        break;
   }
   catch (FormatException)
   {
      continue;
   }
}
celsius = FahrenheitToCelsius(fahrenheit);

请注意,如果是 FormatException,则无需计算,因此我在 catch 块内添加了带有 continuewhile (true) 循环。另外我推荐在这里使用Int32.TryParse 方法,它会将解析结果返回为bool 而不是引发异常。

【讨论】:

  • 哦,我明白了!像你说的那样更改了代码,现在我收到了这个错误:错误 CS0165 Use of unassigned local variable 'celsius'
  • 是的,在这种情况下,第一次运行时 celsius 没有设置,但在 while (celsius &lt; 73 || 77 &lt; celsius); 中使用了,请查看我的更新答案
  • 谢谢!解决了问题!
【解决方案2】:

这里有几个问题。主要的是 Fahrenheit 需要在 try 块之外声明,因为您在该块之外使用它(变量的范围仅限于声明它们的块)。将其移至定义 celsius 的位置似乎是合乎逻辑的,尽管通常最好在所需的最内层范围内声明变量。

第二件事是您应该使用int.TryParse 方法来验证用户输入,而不是使用try/catch 块。它的性能要好得多,而且代码更干净、更有意。阅读this question的答案以获取更多信息。

该方法成功返回true,并传入一个string进行解析(我们直接在下面使用Console.ReadLine()的返回值),以及一个out参数,如果成功。

这些更改可能类似于:

private static void Main(string[] args)
{
    int celsius;

    Console.WriteLine("Hello! Welcome to the sauna!\n");

    do
    {
        // Use a loop with TryParse to validate user input; as long as
        // int.TryParse returns false, we continue to ask for valid input
        int fahrenheit;
        do
        {
            Console.Write("Please enter your desired degrees in Fahrenheit: ");

        } while (!int.TryParse(Console.ReadLine(), out fahrenheit));

        celsius = FahrenheitToCelsius(fahrenheit);

        // Rest of loop code omitted...

    } while (celsius < 73 || 77 < celsius);

    Console.ReadLine();
}

【讨论】:

  • 感谢您解决这个问题,在本课程中必须使用 try/catch,但将来肯定会使用 int.TryParse!
【解决方案3】:

你可以做一些不同的事情。

  1. 您可以在代码顶部靠近int celcisusint fahrenheit
  2. 您可以将所有代码放在try 中,如果有任何失败,它就会被捕获。

【讨论】:

    【解决方案4】:

    您必须在外部范围内声明变量以处理异常,才能拥有一个 calid C# 程序。

    这样,您最终会在转换成功时分配变量,否则您只需向用户重新询问值:

    class Program
    {
        static int FahrenheitToCelsius(int fahrenheit)
        {
            int celsius = ((fahrenheit - 32) * 5) / 9;
            return celsius;
        }
    
        static void Main(string[] args)
        {
            int celsius;
    
            Console.WriteLine("Hello! Welcome to the sauna!");
            Console.WriteLine();
            Console.WriteLine("Please enter your desired degrees in Fahrenheit: ");
            do
            {
                // you have to declare the variable out of the scope
                int fahrenheit;
                try
                {
                    fahrenheit = Convert.ToInt32(Console.ReadLine());
                }
                catch (FormatException)
                {
                    // and here you have to handle the exception
                    Console.WriteLine("Invalid value.");
                    continue;                    
                }
    
                celsius = FahrenheitToCelsius(fahrenheit);
                Console.WriteLine("The sauna is now set to " + fahrenheit + " degrees Fahrenheit, which equals to " + celsius + " degrees Celsius.");
    
                if (celsius < 25)
                {
                    Console.WriteLine("Way too cold! Turn the heat up: ");
                }
                else if (celsius < 50)
                {
                    Console.WriteLine("Too cold, turn the heat up: ");
                }
                else if (celsius < 73)
                {
                    Console.WriteLine("Just a little bit too cold, turn the heat up a little to reach the optimal temperature: ");
                }
                else if (celsius == 75)
                {
                    Console.WriteLine("The optimal temperature has been reached!");
                }
                else if (celsius > 77)
                {
                    Console.WriteLine("Too hot! Turn the heat down: ");
                }
                else
                    Console.WriteLine("The sauna is ready!");
                {
                }
            } while (celsius < 73 || 77 < celsius);
            Console.ReadLine();
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-21
      • 2013-06-01
      • 2010-12-17
      相关资源
      最近更新 更多