我正进入(状态
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
}