为什么在枚举其键时不能更改字典的值? [英] Why can't we change Values of a dictionary while enumerating its keys?

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

问题描述

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;  

            }
        }
    }

我完全理解为什么在枚举列表时会抛出此异常-似乎可以合理地预期在枚举期间,枚举对象的结构不会更改.但是-更改字典的 Value 是否会更改其结构? 具体来说,其键的结构是什么?

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 Framework程序员想要,他们可以很容易地区分对字典结构所做的更改和对字典中的值所做的更改.但是,即使人们反复遍历集合的各个键,他们通常最终还是反而会得到这些值.我怀疑.NET框架设计人员认为,如果要遍历这些值,那么您将想知道是否有什么东西像从任何List一样使它们从您的身下消失了.要么,要么他们认为这不是一个重要的问题,因此不值得在一种变更和另一种变更之间进行区分而需要进行编程和维护.

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天全站免登陆