我想获取在struct中创建的对象。显示代码会更好地解释它。
private void Obstacle()
{
obstacle_pos_x = obstacle_random_x.Next(1000);
obstacle_pos_y = obstacle_random_y.Next(700);
picture = new PictureBox
{
Name = "pictureBox" + obstacle_numb,
Size = new Size(32, 32),
Location = new Point(obstacle_pos_x,obstacle_pos_y),
BackColor = Color.Black,
};
this.Controls.Add(picture);
}
这是Obstacle方法内部的结构。如您所见,此方法创建图片框,我想将其拉入KeyPressEvents。就像,如果按W,则struct创建的所有图片框都必须移动-10(y轴)。
else if (e.KeyCode == Keys.W)
{
y -= chrspeed;
obstacle_numb++;
Obstacle();
for (int i = 0; i <= obstacle_numb; i++)
{
}
}
此事件。但是它只是创建图片框。 For循环为空,因为我不知道该怎么办。我只想做这样的事情,
图片+障碍物编号。位置=新Point(x,y); (我需要这张picture + obstacle_numb组合。)
但也知道这是不可能的。我想到了foreach,但我不知道如何使用它。如果修复,也许像这样的东西可以工作。
foreach(PictureBox objects from picture) //It doesn't work too.
我现在陷入困境,等待您的帮助。预先感谢。
答案 0 :(得分:1)
最简单的方法是迭代所有PictureBox类型的子控件:
...
foreach (var pict in this.Controls.OfType<PictureBox>())
{
// pict is now a Picturebox, you can access all its properties as you have constructed it
// the name was constructed that way: Name = "pictureBox" + obstacle_numb,
if (pict.Name != "pictureBox1")
{
pict.Location = new Point(pict.X, pict.Y-10);
}
}