G'day, у меня, похоже, проблема с переменной класса в моем приложении Windows Form.
Это переменная string
в моем классе Player
. Когда я создаю объект Player
, я не могу присвоить значение string
переменной playerName
.
Я вручную создал свои методы Get
и Set
, и я могу ' Я не вижу ничего плохого в этом.
Я несколько раз получал сообщение, в котором сообщалось, что строка playerName
не назначена и останется значением по умолчанию null
. Я не уверен, почему это так.
class Player
{
private string playerName = ""; //Variable used for giving each player a unique identifier, eg. 'Player One', etc
//public string PlayerName { get => playerName; set => playerName = value; }
public void setPlayerName(string name) //Sets the player's name for the game (UNSC or Covenant)
{
name = this.playerName;
}
public string getPlayerName() //Returns the player's name
{
return playerName;
}
}
Создание класса Player
и попытка показать playerName
в текстовом поле не работает, значение playerName
остается null
public partial class FrmBoardGameApp : Form
{
public FrmBoardGameApp()
{
InitializeComponent();
}
ArrayList Players = new ArrayList();
public void creationOfPlayers() //BUG!!! Values stay null
{
Player playerOne = new Player(); //Player 1
Player playerTwo = new Player(); //Player 2
playerOne.setPlayerName("Player One");
playerTwo.setPlayerName("Player Two");
Players.Add(playerOne); //Player name value is still null at this point
Players.Add(playerTwo);
}
//Here's the textbox assignment code
public bool playerTurn = true; //A bool variable used to keep track of whose turn it is
public bool setupCheck = false; // Ensures that the endturn button cannot be hit unless all setup is done
public int setupCheckValue = 0; //Ensures that the setup button can only be hit once
public void testingPlayerTurn() //A method used to test whose turn it is
{
if (setupCheck != true)
{
MessageBox.Show("Game is not setup, please setup the game");
}
else
{
//Textbox is empty, as playerName value remains null
if (playerTurn)
{
Players.ToArray();
Player firstPlayer = (Player)Players[0];
txtAns.Text = firstPlayer.getPlayerName();
/*
* This method of accessing an element and controlling/manipulating its values works
*/
}
else if (!playerTurn)
{
//playerTwo.setPlayerName(factionTwo);
//txtAns.Text = playerTwo.getPlayerName();
}
}
}
private void btnEndTurn_Click(object sender, EventArgs e) //Ends the turn of the current player
{
changePlayer();
//testingPlayerTurn();
testingPlayerNames();
}
}
Я добавил в пример кода некоторые методы, которые обрабатывают назначение игрока, на случай, если это поможет каким-либо образом. Но проблема начинается с creationOfPlayers
метода и Player
класса.