Skip to main content
 首页 » 编程设计

c#之集合在循环期间被修改,当它不可能是 C#

2024年02月01日31zlslch

以下代码的 foreach 语句抛出一个 InvalidOperationException 说“集合已被修改。枚举操作无法执行。”我不明白这是怎么可能的,因为颜色在初始化后永远无法修改。

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.

这是字典键的 View ...而您正在此处修改字典:

colorDictionary[c]--; 

不可否认,这实际上并没有添加或删除任何键 - 但它正在修改字典,并且键枚举器基本上对此很敏感。

最简单的修复方法就是创建一个副本:

IEnumerable<Color> colors = colorDictionary.Keys.ToList();