【发布时间】:2013-07-21 20:57:59
【问题描述】:
我知道这个异常已经被处理了十亿次,但我的情况略有不同(我认为)。
无论如何,我正在使用 ProtoBuf - Net 来保存和加载对象。我有一个我试图反序列化的对象列表,但它一直在说(它来了):
Collection was modified; enumeration operation may not execute.
再次,我在这里看到这个问题被问了 50 次,所以我很抱歉 50 次,但这里是代码:
public void Load(){
using (var file =
File.Exists(Application.StartupPath + @"\TestFile.scn") ?
File.OpenRead("TestFile.scn") :
null){
if (file != null){
this._tlpGrid.Controls.Clear();
this.Scenes = Serializer.Deserialize<List<GraphicsPanel>>(file);
foreach(GraphicsPanel gp in this._lgpScenes)
this.AddScene(gp);
}
}
}
为什么会抛出该异常?如果我做错了,正确的方法是什么?
编辑:有人告诉我 AddScene 方法正在修改列表。那是对的: 原文:
public void AddScene(GraphicsPanel Scene){
this._tlpGrid.Controls.Add(Scene);
this.Scenes.Add(Scene);
}
修改:
public void AddScene(GraphicsPanel Scene){
this._tlpGrid.Controls.Add(Scene);
if (!this.Scenes.Contains(Scene))
this.Scenes.Add(Scene);
}
问题已经得到解答,非常感谢。
【问题讨论】:
-
AddScene() 是做什么的?
-
我假设
AddScene正在修改_lgpScenes,而在枚举它时你不能这样做。 -
啊啊啊你是对的!!!编辑代码以反映。
-
如果问题已经回答,@lee 请在下面写下答案,以便将其标记为已接受的答案。
标签: c#-4.0 exception protobuf-net