Collection being modified during loop when there is no way it can be C#
以下代码的foreach语句引发一个InvalidOperationException,表示"集合已修改"。枚举操作无法执行。"我看不出这是怎么可能的,因为颜色在初始化之后是无法修改的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | Dictionary<Color, int> colorDictionary = new Dictionary<Color, int>(); //Put stuff in colorDictionary... int currentBest = 257; Color replaceColor = Color.Empty; Dictionary<Color, int>.KeyCollection colors = colorDictionary.Keys; foreach (Color c in colors) { if (colorDictionary[c] == 0) { continue; } if (ColorDistance(color, c) < currentBest) { replaceColor = c; colorDictionary[c]--; } } |
I don't see how this is possible, seeing as colors can never be modified after it's initialization.
这是字典键上的视图…你在修改字典:
1 | colorDictionary[c]--; |
诚然,这并不是在添加或删除任何键,而是在修改字典,而键枚举器基本上对此很敏感。
最简单的修复方法就是创建一个副本:
1 | IEnumerable<Color> colors = colorDictionary.Keys.ToList(); |