我的 Windows Phone 7 silverlight 应用程序在将图钉放置在 map 层上之前删除了之前存在的任何图钉。
我在一个 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.
}
此代码会根据需要删除任何图钉,但在最后一个循环会抛出异常“无效操作”后,我将其重新编写为 for 循环:
for (int i = 0; i < PushPinLayer.Children.Count; i++)
{
if (PushPinLayer.Children[i].GetType() == typeof(Pushpin))
{
PushPinLayer.Children.RemoveAt(i);
}
}
效果很好,但我不明白为什么 foreach 会抛出错误。
最佳答案
这很正常,
您不能从列表中删除仍在 foreach 列表中使用的项目。 比删除项目更好的方法是创建一个新列表,并且每次它不是图钉类型时,将该对象添加到新列表。
这样原始列表就不会改变,你也不会得到异常。
我觉得 for 循环起作用很奇怪,但如果起作用,则意味着它们迭代的方式不同。 for 循环将被复制到另一个内存位置并用于 for 循环,以便 for 循环不再使用您删除项目的原始位置。 foreach 循环将从列表中获取参数,您删除项目,因此列表和参数成为并发的。
关于c# - foreach 和 for 循环之间的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4386032/