每次从矩形数组中删除项目时都会出现异常

问题描述 投票:-1回答:1

我正进入(状态

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();
}
c# drawing invalidoperationexception
1个回答
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
}
© www.soinside.com 2019 - 2024. All rights reserved.