foreach和for循环之间的奇怪行为

Fis*_*ake 3 c# windows-phone-7

我的windows phone 7 silverlight app在将图钉放在地图图层上之前删除了之前存在的任何内容.

我在foreach循环中这样做如下:

            //Clear previous pins
        try
        {
            foreach (UIElement p in PushPinLayer.Children)
            {
                if(p.GetType() == typeof(Pushpin))
                {
                    PushPinLayer.Children.Remove(p);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            //TODO: For some reason the foreach loop above causes an invalid Operation exception.
            //Cathing the error here until I can work out why it is happening.
        }
Run Code Online (Sandbox Code Playgroud)

此代码根据需要删除任何图钉但在最后一个循环之后会抛出异常"无效操作"我将其重新编写为for循环:

        for (int i = 0; i < PushPinLayer.Children.Count; i++)
        {
            if (PushPinLayer.Children[i].GetType() == typeof(Pushpin))
            {
                PushPinLayer.Children.RemoveAt(i);
            }
        }
Run Code Online (Sandbox Code Playgroud)

哪个工作正常,但我不明白为什么foreach抛出错误.

Nea*_*alv 7

这很正常,

您无法从列表中删除仍在foreach列表中使用的项目. 更好的是删除项目将是创建一个新列表,并且每次它不是图钉类型时,将对象添加到新列表.

这样原始列表不会被更改,您将不会获得异常.

我发现for循环有效,但如果确实如此,那就意味着它们的迭代方式不同了.for循环将被复制到另一个内存位置并用于for循环,以便for循环中不再使用删除项目的原始循环.foreach循环将从列表中获取参数,您删除项目,因此列表和参数变为并发.