我在c#中创建了一个简单的Tic-Tac-Toe游戏,到目前为止我只有2种形式。
frmMain.
(主要游戏形式)frmPlayerInfo.
(用于选择单人或2人)我还创建了一个类Player。
所以我的确如此。一旦玩家输入他们的名字,它将转到Player类中的属性并将值存储在私有变量中,以便我可以在主窗体上获取它以用于显示目的。 但当我回到主要形式时,属性会带回null,为什么会这样?
继承我的代码。
播放器类...(我删除了与此问题无关的相关属性和变量)
class Player
{
#region PrivatVariables
private string _PlayerName1;
private string _PlayerName2;
#endregion
#region Properties
public string playerName1
{
get
{
return _PlayerName1;
}
set
{
_PlayerName1 = value;
}
}
public string playerName2
{
get
{
return _PlayerName2;
}
set
{
_PlayerName2 = value;
}
}
#endregion
public Player()
{
// Do nothing
}
internal void resetValues()
{
}
}
主表单...(我刚刚包含主要代码,我在表单加载时调用新游戏代码)
public partial class frmMain : Form
{
Player player = new Player();
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
// TODO : Set timer so that form can load first.
newGame();
}
private void newGame()
{
// Creating an instance of the Form used to take in player info.
frm_PlayerInfo playerInfo = new frm_PlayerInfo();
// This is going to pop up the player info form.
DialogResult dialogResult = playerInfo.ShowDialog();
LoadForm();
}
private void LoadForm()
{
grpBoxPlayer1.Text = player.playerName1;
}
玩家信息表格...()
public partial class frm_PlayerInfo : Form
{
Player player = new Player();
bool isAnimated;
public frm_PlayerInfo()
{
InitializeComponent();
}
private void frm_PlayerInfo_Load(object sender, EventArgs e)
{
// Setting player tow input visibility to false because there will always be one player.
this.txtPlayerName2.Visible = false;
this.lblPlayerName2.Visible = false;
}
private void btnNext_Click(object sender, EventArgs e)
{
btnNext.Visible = false;
// Used to slide the Form up or down.
slideAnimation(ref isAnimated);
}
private void btnStart_Click(object sender, EventArgs e)
{
// Populating the Player Properties
player.playerName1 = this.txtPlayerName1.Text;
if (this.txtPlayerName2.Text != "")
{
player.playerName2 = this.txtPlayerName2.Text;
}
// Calling the animation method to close the animation back up and then the form will be closed.
slideAnimation(ref isAnimated);
FadeOutAnimation();
}
答案 0 :(得分:2)
在frmMain中创建Player类的实例,并将其传递给构造函数中的frmplayerInfo。现在你没有在frmMain中引用Player类。
newGame()
方法中的:
private void newGame()
{
Player player = new Player();
// Creating an instance of the Form used to take in player info.
frm_PlayerInfo playerInfo = new frm_PlayerInfo(player);
// This is going to pop up the player info form.
DialogResult dialogResult = playerInfo.ShowDialog();
LoadForm();
}
并在frm_PlayerInfo类中删除此代码行Player player = new Player();
,并更改它的构造函数:
public partial class frm_PlayerInfo : Form
{
Player player;
public frm_PlayerInfo(Player player)
{
InitializeComponent();
this.player = player;
}
// the rest of the form
另一种选择是让玩家直接在frmPlayerInfo中命名属性。