在我的程序中,我创建了在屏幕上移动的PictureBoxes。我想要这样做,以便用户可以创建尽可能多的这些。为了做到这一点,我创建了一个类,它在创建后被分配给一个图片框并控制它的移动。这适用于picturebox,直到我创建另一个,当它不再受控时。我认为这是因为c#不允许我创建一个类的多个对象,因此结束了以前的创建一个新的。以下是我已经做到了:如何在c#中创建和运行同一类的多个对象?
static ArrayList cps = new ArrayList();
public void ShootCannon() {
Image cubeImage= Image.FromFile("C:\\Users\\Stefan\\Documents\\Visual Studio 2010\\Projects\\Game1\\Game1\\Resources\\CannonCube.png");
PictureBox cannonCube = new PictureBox();
ScreenPanel.Controls.Add(cannonCube);
cannonCube.Image = cubeImage;
cannonCube.SetBounds(cannonCubeInst.X, cannonCubeInst.Y, cubeImage.Width, cubeImage.Height);
cannonCube.BringToFront();
cps.Add(new CubeProjectile(cannonCube));
}
而且CubeProjectile类:
public class CubeProjectile
{
static PictureBox box;
public CubeProjectile(PictureBox box1)
{
box = box1;
Timer Update = new Timer();
Update.Interval = 1;
Update.Tick += new EventHandler(Timer_Tick);
Update.Start();
}
void Timer_Tick(object sender, EventArgs e)
{
Point loc = new Point(box.Location.X, box.Location.Y);
box.SetBounds(loc.X + 1, loc.Y, box.Width, box.Height);
}
}
“C#不允许我创建一个类的多个对象”你在说什么? PictureBox不是单身人士。修复您的私人静态图片框框。 –