为什么会出现"集合被修改;枚举操作可能无法执行"的错误?如何在 C# 中处理此错误?
csharpserver side programmingprogramming更新于 2025/10/2 3:22:17
当循环过程正在对集合(例如:列表)进行操作,并且在运行时修改了集合(添加或删除了数据)时,就会发生此错误。
示例
using System;
using System.Collections.Generic;
namespace DemoApplication {
public class Program {
static void Main(string[] args) {
try {
var studentsList = new List<Student> {
new Student {
Id = 1,
Name = "John"
},
new Student {
Id = 0,
Name = "Jack"
},
new Student {
Id = 2,
Name = "Jack"
}
};
foreach (var student in studentsList) {
if (student.Id <= 0) {
studentsList.Remove(student);
}
else {
Console.WriteLine($"Id: {student.Id}, Name: {student.Name}");
}
}
}
catch(Exception ex) {
Console.WriteLine($"Exception: {ex.Message}");
Console.ReadLine();
}
}
}
public class Student {
public int Id { get; set; }
public string Name { get; set; }
}
}
输出
上述代码的输出是
Id: 1, Name: John Exception: Collection was modified; enumeration operation may not execute.
在上面的例子中,对 studentsList 执行了 foreach 循环。当学生的 ID 为 0 时,该项目将从 studentsList 中移除。由于此更改,studentsList 被修改(调整大小),并在运行时引发异常。
修复上述问题
为了解决上述问题,请在每次迭代开始之前对 studentsList 执行 ToList() 操作。
foreach (var student in studentsList.ToList())
示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace DemoApplication {
public class Program {
static void Main(string[] args) {
var studentsList = new List<Student> {
new Student {
Id = 1,
Name = "John"
},
new Student {
Id = 0,
Name = "Jack"
},
new Student {
Id = 2,
Name = "Jack"
}
};
foreach (var student in studentsList.ToList()) {
if (student.Id <= 0) {
studentsList.Remove(student);
}
else {
Console.WriteLine($"Id: {student.Id}, Name: {student.Name}");
}
}
Console.ReadLine();
}
}
public class Student {
public int Id { get; set; }
public string Name { get; set; }
}
}
上述代码的输出是
输出
Id: 1, Name: John Id: 2, Name: Jack

