c# - 当前上下文中不存在该名称(变量)

标签 c# loops do-while

我的程序中有一个错误,即使在查看了 Stack Overflow 和 Google 上的问题后,我似乎也无法解决该错误。我的程序抛出异常,“当前上下文中不存在名称(变量)。”

do {
      Console.WriteLine("");
      Console.WriteLine("Before you begin, chose a battle to join!");
      Console.WriteLine("1. Battle of Copenhagen - 1801");
      Console.WriteLine("2. Battle of Morton's Ford - 1864");
      Console.WriteLine("3. Battle of Schuinshoogte - 1881");
      Console.WriteLine("4. Battle of Kufit - 1885");
      Console.WriteLine("5. Invasion of Normandy - 1944");

      String stringWarOption = Console.ReadLine();
      int warOption = Convert.ToInt32(stringWarOption);

      switch (warOption){
          case 1:
              //continue all code here
              Console.WriteLine("Loading the Battle of Copenhagen - 1801.");
              break;
          case 2:
              Console.WriteLine("This war is locked, however you can read up about it here: ");
              Console.WriteLine("https://en.wikipedia.org/wiki/List_of_battles_1801%E2%80%931900");
              break;
          case 3:
              Console.WriteLine("This war is locked, however you can read up about it here: ");
               Console.WriteLine("https://en.wikipedia.org/wiki/List_of_battles_1801%E2%80%931900");
              break;
          case 4: 
              Console.WriteLine("This war is locked, however you can read up about it here: ");
              Console.WriteLine("https://en.wikipedia.org/wiki/List_of_battles_1801%E2%80%931900");
              break;
          case 5:
              Console.WriteLine("This war is locked, however you can read up about it here: ");
              Console.WriteLine("https://en.wikipedia.org/wiki/Invasion_of_Normandy");
              break;
          default:
              break;
      }
  }
  while (warOption != 1);

最佳答案

您正在声明 warOption在你的do里面 block ,但在 do 之外引用它阻止您的 while声明:

do {
    /* ... */
    int warOption = Convert.ToInt32(stringWarOption);
    /* ... */
} while (warOption != 1);

该变量未在该范围内定义。移动warOption的声明到您的do之前 block :

int warOption;

do {
    /* ... */
    warOption = Convert.ToInt32(stringWarOption);
    /* ... */
} while (warOption != -1);

关于c# - 当前上下文中不存在该名称(变量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32001241/

相关文章:

python - 迭代 groupby 数据帧以在每一行中进行操作

将 c 顺序转换为 OpenMP 问题

c++ - 为什么我的 do while 循环中会得到一个额外的字符?

c# - 无法从 'ref object' 转换为 'tagVARIANT*'

c# - 更改布局大小取决于屏幕大小

c# - 在C#方法定义的返回类型前加 'new'?

c# - 可以在没有循环的情况下做到这一点吗?

C# 递归方法返回空引用,对象引用未设置为对象的实例。 XElement 对象

loops - 在 groovy 中以优雅的方式做事

java - for 循环内的 do-while 循环