C# 全局变量未更新

问题描述 投票:0回答:1

不确定我做错了什么,这是我正在做的一个例子:

public class Game
{
   int[,] board = new int[9, 9];
   int gridRow = -1;
   int gridCol = -1; // set to -1 so they will be invalid for a loop that randomly places items during newGame() (not shown) while not invalid and not an already occupied index

   void playGame()
   {
      // main logic loop
      getMove();
      doMove();
   }

   void getMove()
   {
      string grid = Console.ReadLine(); // there is more logic to check for certain inputs... skip
      if (char.ToUpper(grid[0]) >= 'A' && char.toUpper(grid[0]) <= 'I')
      {
         gridCol = (char.ToUpper(grid[0]) - 64) -1;
         gridRow = grid[1] - 1;
      }
   }

   void doMove()
   {
      // do stuff with board[gridRow, gridCol]
   }
}

doMove() 抛出 IndexOutOfRangeException,表示 gridRow 和 gridColumn 仍为 -1,如何更新这些变量?

c# global-variables
1个回答
0
投票

尝试这样的 Somting

void getMove()
{
    Console.WriteLine("Enter number: ");

    int number;
    if(!Int32.TryParse(input, out number))
    {
        //throw exception, Or default number
    }
    gridRow = number;
}
© www.soinside.com 2019 - 2024. All rights reserved.