【问题标题】:Trying to enumerate over a deserialized list throws an exception尝试枚举反序列化列表会引发异常
【发布时间】: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


【解决方案1】:

很明显,问题在于我调用来修改列表的方法在迭代列表时正在修改列表。这应该很明显,但我完全错过了。谢谢你告诉我,李。 抛出异常的方法代码:

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);
                }
            }
}

以及导致问题的方法(之前):

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);
}

再次感谢您耐心地指出显而易见的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-22
    • 2019-05-31
    • 2015-07-26
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    相关资源
    最近更新 更多