我有List<ActiveDeviceProcess>
来保存窗体。当我通过activeDeviceProcessFormClosed(deviceNumber)
听众从另一个表单中调用FormClosing
时。我收到了一个错误。但我不知道为什么。一切看起来都很好。这是我的方法:
public void activeDeviceProcessFormClosed(int deviceNumber)
{
this.Invoke((MethodInvoker)delegate
{
foreach (ActiveDeviceProcess i in activeDeviceProcessForms)
{
if (i.device.deviceNumber == deviceNumber)
{
activeDeviceProcessForms.Remove(i);
}
}
});
}
这是错误:
mscorlib.dll中出现“System.InvalidOperationException”类型的异常,但未在用户代码中处理
感谢您的帮助!
答案 0 :(得分:3)
迭代时,您无法从集合中删除项目。请改用List<T>.RemoveAll
:
public void activeDeviceProcessFormClosed(int deviceNumber)
{
this.Invoke((MethodInvoker)delegate
{
activeDeviceProcessForms.RemoveAll(i => i.Device.DeviceNumber == deviceNumber);
});
}
修改强>
如果您只有多个具有相同设备ID的项目想删除具有DeviceNumber
的第一个元素,则可以使用Enumerable.FirstOrDefault
和List<T>.Remove
:
public void activeDeviceProcessFormClosed(int deviceNumber)
{
this.Invoke((MethodInvoker)delegate
{
var device = activeDeviceProcessForms.FirstOrDefault(
i => i.Device.DeviceNumber == deviceNumber);
if (device != null)
activeDeviceProcessForms.Remove(device);
});
}
答案 1 :(得分:0)
因为它是迭代的,当我删除列表中的一个元素时,我应该添加&#34; break&#34;命令。
public void activeDeviceProcessFormClosed(int deviceNumber)
{
this.Invoke((MethodInvoker)delegate
{
foreach (ActiveDeviceProcess i in activeDeviceProcessForms)
{
if (i.device.deviceNumber == deviceNumber)
{
activeDeviceProcessForms.Remove(i);
break;//----> this was added.
}
}
});
}