[英]Index was out of range c#
為什么我得到的索引超出范圍? 我看了很多遍代碼,卻找不到錯誤所在。 這是清單:
List<PictureBox> bullets = new List<PictureBox>();
int i=0;
事件KeyDown:
void Tank_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData== Keys.space)
{
if (bullets.Count==0)
{
PictureBox bullet = new PictureBox();
kulka.Name = Convert.ToString(i);
kulka.Image = new Bitmap("foto/kulka2.png");
Random dd = new Random();
if (pagr.Name == "RotateW")
bullet.Location = new Point(pagr.Location.X + 16, pagr.Location.Y - 8);
if (pagr.Name == "RotateS")
bullet.Location = new Point(pagr.Location.X + 16, pagr.Location.Y + pagr.Height + 2);
if (pagr.Name == "RotateA")
bullet.Location = new Point(pagr.Location.X - 8, pagr.Location.Y + 16);
if (pagr.Name == "RotateD")
bullet.Location = new Point(pagr.Location.X + pagr.Height + 11, pagr.Location.Y + 16);
bullet.Width = 5;
bullet.Height = 8;
bullet.SizeMode = PictureBoxSizeMode.StretchImage;
bullet.BringToFront();
bullets.Add(bullet);
panelis.Controls.Add(bullets[i]);
Task task = new Task(() => this.bullet_move(i, pagr.Name));
task.Start();
this.Refresh();
}
}
}
這是我的任務:
void bullet_move(int j,string rotation)
{
while (true)
{
if (rotation == "RotateW")
{
BeginInvoke(new Action(() => bullets[j].Top = bullets[j].Top - 1));
if (bullets[j].Top < 2)
{
BeginInvoke(new Action(() => panelis.Controls.Remove(bullets[j])));
bullets.RemoveAt(j);
Application.DoEvents();
i = 0;
break;
}
}
}
}
有時我到達這里索引超出范圍:
BeginInvoke(new Action(() => bullets[j].Top = bullets[j].Top - 1));
有時在這里:
BeginInvoke(new Action(() => panelis.Controls.Remove(bullets[j])));
為什么會出現該錯誤? :/ 感謝幫助... :)
我首先將Invoke替換BeginInvoke。 BeginInvoke是一個異步調用,您正處於一個非常緊密的循環中。 調用可能無法按其執行順序執行。 這將使代碼幾乎無法調試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.