【问题标题】:Variable doesn't exist in current context in for loopfor循环中的当前上下文中不存在变量
【发布时间】:2015-11-29 14:55:32
【问题描述】:

这可能是一件非常明显的事情,并且可能会让我投反对票,但是... Visual Studio 告诉我 int iif/else 声明的当前上下文中不存在。这是怎么回事?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LongSequence
{
    class Program
    {
        static void Main()
        {
            int numberToPrint;

            for (int i = 2; i <= 1000; i++);
            {  
                if (i % 2 == 0)

                    numberToPrint = i;
                else 
                    numberToPrint = i *(-1);
                Console.WriteLine(numberToPrint);  
            }
        }
    }
}

【问题讨论】:

  • forstatement 的末尾删除;

标签: c# visual-studio for-loop


【解决方案1】:
for (int i = 2; i <= 1000; i++);

由于;,此循环没有正文。所以它根本没有做任何事情。 因此,您的其他代码被视为另一条语句,它在循环范围之外,其中创建了变量i

【讨论】:

    【解决方案2】:

    For 循环不应该有一个终止,在你的代码中,它会给出一个错误,因为它在那里终止。所以之后没有定义 i 的值,像下面这样改变它

    for (int i = 2; i <= 1000; i++)
        {
         if (i % 2 == 0)
             numberToPrint = i;
         else 
             numberToPrint = i *(-1);
             Console.WriteLine(numberToPrint);
         }
    

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-17
      • 2013-05-13
      • 2023-03-05
      相关资源
      最近更新 更多