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

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

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改变事件的次数也不同。以下方式只触发一次:string

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

相关文章
相关标签/搜索