簡體   English   中英

每次從矩形數組中刪除項目時都會出現異常

[英]Getting exception every time I delete an item from rectangle array

我正進入(狀態

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();
}

您可能需要使用 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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM