收藏集已修改;枚举操作可能无法执行.当更新哈希表的值时 [英] Collection was modified; enumeration operation may not execute. when update values of hashtable

查看:75
本文介绍了收藏集已修改;枚举操作可能无法执行.当更新哈希表的值时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试更新值时,此代码引发异常,仅更新第一个值,然后引发异常集合已修改;枚举操作可能无法执行." !!!!

this code throw exception while i am trying to update value ,first value only updated and then throw the exception "Collection was modified; enumeration operation may not execute." !!!!

        Hashtable hh = new Hashtable();
        hh.Add("val 1",null);
        hh.Add("val 2", null);

        foreach (string dd in hh.Keys)
        {
            hh[dd] = "some_value";
           // MessageBox.Show(dd.Value.ToString());
        }

我需要更新哈希表或具有[key,value]的任何等效结构中的空值?

i need to update empty values in hashtables or any equivalent structure that has [key,value]??

推荐答案

您需要制作hh.Keys的副本,因为您试图更改Hashtable,而该哈希表是无效操作,同时在foreach循环中枚举其键.

You need to make copy of hh.Keys, because you are trying to change Hashtable which is invalid operation while enumerating its keys in the foreach loop.

尝试此代码

foreach (string dd in new List<object>(hh.Keys.Cast<object>()))
{
    hh[dd] = "some_value";
    MessageBox.Show(dd);
}

这篇关于收藏集已修改;枚举操作可能无法执行.当更新哈希表的值时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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