每次我从矩形数组中删除项目时都会获取异常

时间:2019-03-02 01:26:48

标签: c# drawing invalidoperationexception

我得到

  

System.InvalidOperationException:'集合已被修改;枚举操作可能无法执行。

每次我想从数组中删除一个项目时,都可以在该位置绘制(填充)另一个矩形。

MouseDown事件中发生的所有事情都应该在右黑色矩形上绘制(填充),在左白色矩形上绘制。

我列出了2个矩形列表,一个用于白色,一个用于黑色。

当我尝试绘制(填充)具有相反颜色的矩形时,出现异常。

所有内容均写入位图,随后在Paint事件中将位图绘制为图像。

 private void Form1_MouseDown(object sender, MouseEventArgs e)
 {
        if (e.Button == MouseButtons.Right)
        {
                using (Graphics rectGraphics = Graphics.FromImage(rectBitmap))
                {
                    rBlack = new Rectangle((e.X / 20) * 20, (e.Y / 20) * 20, 20, 20);

                    rectGraphics.SmoothingMode = SmoothingMode.HighSpeed;


                    foreach (Rectangle r in whiteRectangles) // place where exception is thrown if I want to fill black rectangle on the place where white is
                    {
                            if (r.X - 1 == rBlack.X && r.Y - 1 == rBlack.Y)
                            {
                                int index = whiteRectangles.IndexOf(r);
                                whiteRectangles.RemoveAt(index);
                            }

                            rectGraphics.FillRectangle(brushWhite, r);
                    }

                    blackRectangles.Add(rBlack);

                    foreach (Rectangle r in blackRectangles)
                    {
                        rectGraphics.FillRectangle(brushBlack, r);
                    }
              }
        }

        if (e.Button == MouseButtons.Left)
        {
                using (Graphics rectGraphics = Graphics.FromImage(rectBitmap))
                {
                    rWhite = new Rectangle((e.X / 20) * 20 +1, (e.Y / 20) * 20 +1, 19, 19);
                    rectGraphics.SmoothingMode = SmoothingMode.HighSpeed;

                    foreach (Rectangle r in blackRectangles) // place where exception is thrown if I try to fill white rectangle on the place where black is
                    {
                            if (r.X + 1 == rWhite.X && r.Y + 1 == rWhite.Y)
                            {
                                int index = blackRectangles.IndexOf(r);
                                blackRectangles.RemoveAt(index);
                            }

                            rectGraphics.FillRectangle(brushBlack, r);
                    }

                    whiteRectangles.Add(rWhite);

                    foreach (Rectangle r in whiteRectangles)
                    {
                        rectGraphics.FillRectangle(brushWhite, r);
                    }
              }
        }

        this.Refresh();
}

1 个答案:

答案 0 :(得分:0)

您可能需要使用for循环而不是foreach。使用列表的“计数”设置上限,然后按索引删除。

for (int i = 0; i < list.Count; i++)
{
 //Delete list[i] here
}

或者相反

for (int i = list.Count - 1; i >= 0; i--)
{
 //Delete list[i] here
}