我们为什么不能改变字典的价值,同时列举了钥匙? [英] Why cant we change Values of a dictionary while enumerating its keys?

查看:128
本文介绍了我们为什么不能改变字典的价值,同时列举了钥匙?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Program
    {
        static void Main(string[] args)
        {
            var dictionary = new Dictionary<string, int>()
            {
                {"1", 1}, {"2", 2}, {"3", 3}
            };

            foreach (var s in dictionary.Keys)
            {
                // Throws the "Collection was modified exception..." on the next iteration
                // What's up with that?

                dictionary[s] = 1;  

            }
        }
    }



我完全明白为什么列举似乎有理由期待枚举期间,枚举对象的结构不改变列表 - 当这种异常。 However-不会改变字典的的的改变它的结构的?
具体来说,它的钥匙?结构

I completely understand why this exception is thrown when enumerating a list- it seems reasonable to expect that during enumeration, the Structure of the enumerated object does not change. However- does changing a Value of a dictionary changes its Structure? Specifically, the structure of its keys?

推荐答案

我看到你从哪里来,其实。然而,大多数的答案在这里没有注意到的是,你可以访问密钥列表中迭代,而不是字典的项本身。如果.NET框架程序员愿意,他们可以很容易的字典和词典中的值所做的更改结构的变化做出区分。然而,即使当人们跨越集合的键然后遍历,他们通常最终得到的值还行吧。我怀疑在.NET框架的设计者认为,如果你是跨这些值迭代,你要知道,如果事情是从下你改变他们,丝毫不亚于任何名单。如果不是这样,他们没有看到它作为一个足够重要的问题,值得的编程和维护,将需要一种变革和另一个区分开来。

I see where you're coming from, actually. What most of the answers here fail to notice is that you are iterating across the list of Keys, and not the Dictionary's Items themselves. If the .NET framework programmers wanted to, they could fairly easily differentiate between changes made to the structure of the dictionary and changes made to the values in the dictionary. Nevertheless, even when people iterate across the keys of a collection, they usually end up getting the values out anyway. I suspect the .NET framework designers figured that if you're iterating across those values, you'll want to know if something is changing them out from under you, just as much as with any List. Either that or they didn't see it as an important enough issue to merit the programming and maintenance that would be required to differentiate between one kind of change and another.

这篇关于我们为什么不能改变字典的价值,同时列举了钥匙?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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