c# - 不能声明局部变量名称 'choice',因为它会给 'choice' 不同的含义

标签 c# if-statement while-loop do-while

抱歉,我是编程界的新手。我正在创建一个控制台应用程序,它基本上会根据您的输入来确定您是想将摄氏温度转换为华氏温度,还是相反。

我遇到的问题是:

"Error 3 A local variable named 'choice' cannot be declared in this scope because it would give a different meaning to 'choice', which is already used in a 'parent or current' scope to denote something else"

我尝试查看其他示例,但它们远比我的大脑现在能够理解的复杂得多。

namespace TemperatureApp
{
    class Program
    {
        static void Main(string[] args)
        {
            int choice;

            do
            {
                Console.WriteLine("Hi! This is a temperatue app");
                Console.WriteLine("Press 1 for C to F or 2 for F to C");
                //take the user input
                int choice = Convert.ToInt32(Console.ReadLine());


                if (choice == 1)
                {
                    Console.WriteLine("Great, you chose C to F. Now enter the temp.");
                    int celcius = Convert.ToInt32(Console.ReadLine());
                    //next line use the formula and show answer
                }
                if (choice == 2)
                {
                    Console.WriteLine("Great, you chose F to C. Now enter the temp.");
                    int fahrenheit = Convert.ToInt32(Console.ReadLine());
                    //next line use the formula and show answer
                }
                else
                    Console.WriteLine("That is not the right choice.");
                    //In this way, keep asking the person for either 1 or two

            }
            while (choice != 1 || choice != 2);

            Console.ReadLine();
        }
    }
}

最佳答案

int choice = Convert.ToInt32(Console.ReadLine());

应该阅读

choice = Convert.ToInt32(Console.ReadLine());

通过将 int 放入第二次,您在 {} 中声明了另一个名为“choice”的变量。该定义与外部的定义相冲突。

关于c# - 不能声明局部变量名称 'choice',因为它会给 'choice' 不同的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14781218/

相关文章:

c - 如何在C程序中用汇编语言编写while循环\if语句?

c - for 和 if 条件给出意想不到的结果

c# - 如何使用httpClient在没有太多请求的情况下循环通过rest api

php - 更新查询不在 while 循环中执行

c# - 如何阻止通过 HttpWebRequest 访问 Web 应用程序?

c# - 在 Entity Framework 中添加具有多对多关系的项目

c# - 如何在多线程应用程序中正确卸载AppDomain?

javascript - 如何从数据库中回显 If 语句

java - 如果您检查的网格中没有任何内容,如何返回零?

c# - 当原始请求为 HTTPS 时,AspNetCore.WsFederation 获取 signin-wsfed 重定向到 HTTP