我可以在Main方法中更改类方法中的变量吗?

时间:2017-07-18 11:31:51

标签: c# variables methods scope

我正在学习C#并且正在制作Naughts and Crosses游戏。 我已经达到了一个点,我有一个布尔变量决定玩家转弯,一个玩家想要转弯的输入和实际的棋盘在它自己的班级。

这是我被困的地方。我想接受播放器输入并使用它来更改电路板,但无法弄清楚如何从Main方法访问它。

以下是我的代码。 playerinput指板上的1-9位置,打印机是Board对象。

class Program
{
    static void Main(string[] args)
    {
        ---
        ---
        ---

        int playerinput = printer.GetNumber();

        if (!currentPlayer)
        {
        // I want to add code here that takes playerinput 
        // and changes the corresponding place on the board.
        }

这是实际的董事会。

    public class Board
{ ----
public void PrintBoard()
    {
        var a = 1;
        var b = 2;
        var c = 3;
        var d = 4;
        var e = 5;
        var f = 6;
        var g = 7;
        var h = 8;
        var i = 9;

        System.Console.Writeline(string.Format(@" {0} | {1} | {2}
-----------
 {3} | {4} | {5} 
-----------
 {6} | {7} | {8} ", a, b, c, d, e, f, g, h, i));

所以我需要获取playerinput并更改PrintBoard方法中的相应字母。只要我能改变这些变量,我就应该没问题。

在寻找答案时遇到的一个困难就是知道如何正确地说出来,所以对此主题的任何建议或补充阅读都会受到赞赏。

3 个答案:

答案 0 :(得分:0)

您可以在PrintBoard方法中添加参数。可能看起来像这样

public void PrintBoard(int playerInput)
{
    ....

当您从PrintBoard方法调用Main方法时,您可以向用户提供方法输入并在其中使用。

可能看起来像这样(假设board是您的Board类的实例。

int playerinput = printer.GetNumber();
board.PrintBoard(playerInput);

您可以查看Method Parameters以获取更多信息。

答案 1 :(得分:0)

您可以向方法PrintBoard()添加参数,并可以从Main方法传递参数,如PrintBoard(1,2):

public void PrintBoard(int a, int b)

然后您可以在PrintBoard方法中分配数字,如:

     public void PrintBoard(int a, int b)
    {
    //Can print the numbers directly.
    }

答案 2 :(得分:0)

PrintBoard中的变量不是持久的 - 它们最多只能持续一次。当您再次致电PrintBoard时,任何更改都将丢失。

您需要在足够长的范围内声明电路板。例如,Main方法本身。你已经有了一个Board对象的实例,所以这就是显而易见的地方 - 只需将这些变量声明为字段,而不是方法中的本地变量。

Board对象上的一个方法可能是处理播放器输入;这只是一个将玩家输入作为参数的方法,并相应地更新棋盘。

作为另一个建议,请考虑阅读数组 - 它们是管理结构化数据的便捷方式,例如您在此处使用的网格。你可以这样做:

public class Board
{
  private char[,] data = new char[3, 3]; // A 2D array of ' ', 'X' or 'O'

  // Returns false for invalid input
  public bool HandleInput(int playerInput, char player)
  {
    if (player != 'X' && player != 'O') return false; // Bad player

    // Get coördinates from the 1-9 input
    var x = (playerInput - 1) % 3;
    var y = (playerInput - 1) / 3;

    if (x < 0 || x > 2 || y < 0 || y > 2) return false; // Out-of-board-exception

    if (data[x, y] != ' ') return false; // Non-empty cell

    data[x, y] = player; // Set the new cell contents

    return true;
  }

  public void Print()
  {
    for (var y = 0; y < 2; y++)
    {
      for (var x = 0; x < 2; x++)
      {
        Console.Write(data[x, y]);
        Console.Write(" | ");
      }

      Console.WriteLine();
      Console.WriteLine("---------");
    }
  }
}