为什么我会收到异常InvalidOperationException?

时间:2013-02-24 22:59:27

标签: c# winforms listbox

我编写了以下代码,用于从listBox中删除所选值。我还想将它从字典列表中删除,然后将其更新/写入文本文件,这样当我再次运行程序并加载文本文件时,如果不是,它会在每次运行时都显示已删除的项目申请再次。

private void listBox1_KeyDown(object sender, KeyEventArgs e)
        {
            string sb;
            if (e.KeyCode == Keys.Delete)
            {
                if (this.listBox1.SelectedIndex >= 0)
                {
                    string obj = this.listBox1.SelectedValue.ToString();
                    data.Remove(obj);
                    listBox1.DataSource = null;
                    listBox1.DataSource = data;
                    foreach (KeyValuePair<string, List<string>> kvp in LocalyKeyWords)
                    {
                        for (int i = 0; i < kvp.Value.Count(); i++)
                        {
                            sb = "Url: " + kvp.Key + " --- " + "Local KeyWord: " + kvp.Value[i] + Environment.NewLine;
                            LocalyKeyWords.Remove(kvp.Key);
                        }
                    }

                }
            }

        }

LocalyKeyWords是一个词典&gt;

在这种情况下,它包含两个项目/键我删除了一个,我看到一个断点,这个已被删除。

问题是我是否需要删除kvp.Key或者以某种方式删除我从listBox中移除的项目,这是我想要从LocalyKeywords中删除的项目,它是obj变量,因为即时通讯:

data.Remove(obj);

所以也许我需要从localyKeyWords中删除obj?

我从错误中获得的错误是在从LocalyKeyWords中删除项目后,点击此处继续点击:

foreach (KeyValuePair<string, List<string>> kvp in LocalyKeyWords)

我得到错误:

收藏被修改;枚举操作可能无法执行

System.InvalidOperationException was unhandled
  HResult=-2146233079
  Message=Collection was modified; enumeration operation may not execute.
  Source=mscorlib
  StackTrace:
       at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
       at System.Collections.Generic.Dictionary`2.Enumerator.MoveNext()
       at GatherLinks.Form1.listBox1_KeyDown(Object sender, KeyEventArgs e) in d:\C-Sharp\GatherLinks\GatherLinks\GatherLinks\Form1.cs:line 959
       at System.Windows.Forms.Control.OnKeyDown(KeyEventArgs e)
       at System.Windows.Forms.Control.ProcessKeyEventArgs(Message& m)
       at System.Windows.Forms.Control.ProcessKeyMessage(Message& m)
       at System.Windows.Forms.Control.WmKeyChar(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ListBox.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at GatherLinks.Program.Main() in d:\C-Sharp\GatherLinks\GatherLinks\GatherLinks\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

2 个答案:

答案 0 :(得分:9)

您正在迭代它时从LocalyKeyWords删除项目;这是不允许的,正如异常消息所示。

我不确定这里的大局是什么,但本地解决方案是制作LocalyKeyWords的临时副本并对其进行迭代。然后,您可以毫无困难地修改“源”集合。

示例:

foreach (var kvp in LocalyKeyWords.ToList())  // .ToList() makes a temp copy

答案 1 :(得分:1)

您无法修改foreach内的IEnumerable集合。

您可以创建字典的副本,并通过它修改原始字典。