我正在制作一个带有Button Array
的小型tic tac toe游戏,并且我正在创建数组,我想知道是否有一种更优雅的方式来为它们分配数组。
我目前的代码是:
MovementPiece[0, 0] = button1;
MovementPiece[0, 1] = button2;
MovementPiece[0, 2] = button3;
MovementPiece[1, 0] = button4;
MovementPiece[1, 1] = button5;
MovementPiece[1, 2] = button6;
MovementPiece[2, 0] = button7;
MovementPiece[2, 1] = button8;
MovementPiece[2, 2] = button9;
我现在的问题是我的程序无法看到按钮,因为它们是在本地声明的。
public void Form1_Load(object sender, EventArgs e)
{
Button[,] MovementPiece = { { button1, button2, button3 },
{ button4, button5, button6 },
{ button7, button8, button9 } };
//Initiates the button array.
for (int Row = 0; Row <= 2; Row++)
{
for (int Column = 0; Column <= 2; Column++)
{
this.Controls.Add(MovementPiece[Row, Column]);
//Sets the handler for the buttons.
MovementPiece[Row, Column].Click += new EventHandler(MovementPiece_Click);
}
}
Public void Clear()
{
//Can not see buttons.
}
谢谢,我是一个开始,所以放轻松:|
答案 0 :(得分:2)
当然你可以使用这样的数组初始化器:
Button[,] MovementPiece = { { button1, button2, button3 },
{ button4, button5, button6 },
{ button7, button8, button9 }
};
进一步阅读
答案 1 :(得分:1)
不要使用这样的数组,而是将所有按钮移动到面板中。 (它是一个控件)你可以循环访问面板&#34; Controls&#34;列表。
foreach(Button button IN mypanel.Controls){
//do stuff
}
更容易使用。
答案 2 :(得分:1)
正如我在评论中所述,您需要在类级别声明您的数组,并在Form_Load事件处理程序中初始化它,这样整个表单都可以看到它。这样的事情应该有效。
public partial class Form1 : Form
{
Button[,] MovementPiece; //Declare at the class level
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MovementPiece = new Button[,]{ { button1, button2, button3 },
{ button4, button5, button6 },
{ button7, button8, button9 }
}; //Initialized in your Form Load event
// Do your button initialization here
}
}