源动力

程序在于积累和思考
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C#在foreach循环中修改字典等集合出错的处理

Posted on 2014-08-26 16:37  老K的幸福生活  阅读(3696)  评论(0编辑  收藏  举报

C#在foreach循环中修改字典等集合出错:System.InvalidOperationException: Collection was modified; enumeration operation may not execute.这是因为在foreach中不允许修改集合,可通过如下方式修改dictPublish的值,如:

Dictionary<string, string> _dict = new Dictionary<string, string>(dictPublish);
 if ((_dict != null) && (_dict.Count != 0))
{
      foreach (KeyValuePair<string, string> item in _dict)
      {
            dictPublish[item.Key] = "";
       }
}

如果用直接赋值的方式,如Dictionary<string, string> _dict = dictPublish;也是不行的,会报同样的错误。理由嘛,引用类型所致。

WinForm中绑定到下拉框的数据源的成员设定顺序不同,则会触发SelectedIndex改变事件的次数也不一样。如下方式只触发一次:

ddl.DataSource=null;
ddl.ValueMember="Key";
dd.DisplayMember="Value";
dd.DataSource=new BindingSource(dict,null);
如果数据源不为空的话,默认绑定到第一项,此时如果还有ddl.SelectedIndex=0则不引发索引改变事件。