我正在开发一个利用 Maps 包的 Xamarin.Forms 应用程序。Map 对象包含一个 IList Pins,它存储包含 Label、Position 和其他属性的 Pin 对象列表。我试图通过将它们的位置与包含相同属性(ID、位置等)的自定义对象的集合进行比较来更新此 Pin 图列表,以及它们是否不再存在于此列表中,并相应地删除它们。
为了详细说明,每次更新时,我都想遍历 Pins 列表,删除不再与集合中的对象对应的所有引脚,添加与集合中的新对象对应的所有引脚,并更改任何引脚的位置相应对象的位置发生了变化。
我试图通过迭代引脚并在必要时删除、添加和更改引脚时进行相应的比较来做到这一点。这里的问题是每次删除 Pin 时都会出现以下错误:
An exception of type 'System.InvalidOperationException' occurred in mscorlib.dll but was not handled in user code
Collection was modified; enumeration operation may not execute.
这在修改正在迭代的列表时是可以预料的,但是所有可用的解决方案都可以解决这个问题,例如在实例化 foreach 循环时使用 Maps.Pins.ToList() ,使用 for 循环而不是 foreach循环,甚至创建 Pins 列表的副本以在修改原始列表时进行迭代,都不能解决这个问题。
我知道其中一些解决方案有效,因为我在比较自定义对象列表时使用它们来克服这个问题,但由于某种原因,它们似乎都不适用于 Map.Pins 列表。谁能指出我可能做错了什么,或者是否有一些关于 Map.Pins 列表的细节将其排除在这些解决方案之外?有没有其他方法可以解决这个问题?
作为参考,这里有一些方法,在代码中,我尝试实现“删除不应该再存在的引脚”功能:
.ToList()
foreach (Pin pin in map.Pins.ToList())
{
if (!newList.Any(x => x.ID == pin.Label))
{
Debug.WriteLine("Pin " + pin.Label + " is being removed.");
map.Pins.Remove(pin);
}
}
循环
for (int i = 0; i < map.Pins.Count; i++) {
Debug.WriteLine(map.Pins[i].Label);
if (!newList.Any(x => x.ID == map.Pins[i].Label))
{
Debug.WriteLine("Pin " + map.Pins[i].Label + " is being removed.");
map.Pins.Remove(map.Pins[i]);
}
}
创建新列表
List<Pin> oldPins = new List<Pin>();
foreach (Pin pin in map.Pins)
{
oldPins.Add(pin);
}
foreach (Pin pin in oldPins)
{
if (!newList.Any(x => x.ID == pin.Label))
{
Debug.WriteLine("Pin " + pin.Label + " is being removed.");
map.Pins.Remove(pin);
}
}
// I tried this with the for loop solution as well
首先十分感谢