C# 私有类变量在窗体之间不断重置
我正在用c#创建一个简单的井字游戏,到目前为止我只有两种形式C# 私有类变量在窗体之间不断重置,c#,forms,winforms,C#,Forms,Winforms,我正在用c#创建一个简单的井字游戏,到目前为止我只有两种形式 frmMain.(主要游戏形式) frmPlayerInfo.(用于选择单人或双人) 我还创建了一个类播放器 所以我的想法是这样的。一旦玩家输入他们的名字,它将转到玩家类中的属性,并将值存储在私有变量中,这样我就可以在主窗体上获取它,以便于显示。 但当我回到主形式时,属性返回null,这是为什么 这是我的密码 玩家类。。。(我已删除与此问题无关的I相关属性和变量) 主要形式。。。(我刚刚包括了主代码,我称之为表单加载上的新游戏代码
(主要游戏形式)frmMain.
(用于选择单人或双人)frmPlayerInfo.
在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中添加玩家名称属性。添加代码,在其中填充玩家。我认为您的“主窗体”player
与“玩家信息窗体”player
不同。它们是独立的。但这只是一种假设。你需要显示“玩家信息表单”的玩家声明和初始化的代码。大家好,编辑后请现在查看,我正在填充开始按钮上的玩家属性,请查看代码的最后一部分。大家好,我在主表单中有一个玩家类的实例,它位于代码的顶部,我会包括它现在,请审查后,它是向上的,但它不是同一个实例。。。在frmPlayerInfo中,您创建了一个新的Player实例,而frmMain无权访问它。我明白您的意思,那么我如何使用相同的实例表单作为Player信息表单的主表单?这就是我在回答中写的:您以第一种形式创建实例,并将其传递给构造函数中的第二个实例…那么您建议将实例作为引用传递吗?就像这样。。。frm_PlayerInfo PlayerInfo=新frm_PlayerInfo(参考球员);
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();
}
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();
}
public partial class frm_PlayerInfo : Form
{
Player player;
public frm_PlayerInfo(Player player)
{
InitializeComponent();
this.player = player;
}
// the rest of the form