“Collection is modified ...”问题 [英] "Collection was modified..." Issue

查看:231
本文介绍了“Collection is modified ...”问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数来检查对象列表,看看它们是否被点击,并相应地触发OnClick事件。我相信函数正常工作,但我有一个问题:



当我挂钩到一个OnClick事件,并删除并插入元素到不同的位置在列表中(这个程序的典型功能),我得到集合被修改...错误。



我相信我明白发生了什么: p>


  • 该函数循环遍历每个对象,在必要时触发OnClick事件

  • 一个事件被触发,



b

我的问题是,我如何允许函数遍历所有的对象,在适当的时间触发必要的事件,并仍然给用户选择操纵对象的位置在列表中?

解决方案

这种问题有两种常见的解决方案:




  • 制作列表的副本。迭代该副本。

  • 列出需要更改的列表。在完成迭代后应用更改。



使用索引选项似乎不适合,解耦从执行循环的代码进行更改的代码。


I've got a function that checks a list of objects to see if they've been clicked and fires the OnClick events accordingly. I believe the function is working correctly, however I'm having an issue:

When I hook onto one of the OnClick events and remove and insert the element into a different position in the list (typical functionality for this program), I get the "Collection was modified..." error.

I believe I understand what is going on:

  • The function cycles through each object firing OnClick events where necessary
  • An event is fired and the object changes places in the list per the hooked function
  • An exception is thrown for modifying the collection while iterating through it

My question is, how to do I allow the function to iterate through all the objects, fire the necessary events at the proper time and still give the user the option of manipulating the object's position in the list?

解决方案

There are two general solutions to this kind of problem:

  • Make a copy of the list. Iterate over the copy.
  • Make a list of the changes that need to happen. Apply the changes after you've finished iterating.

The "use indices" option doesn't sound like it's suitable if you want to decouple the code that makes the changes from the code that does the looping.

这篇关于“Collection is modified ...”问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆