为什么会出现“集合已修改;枚举操作可能无法执行”错误,以及如何在 C# 中处理它?
当在集合(例如:List)上运行循环过程并且在运行时修改了集合(添加或删除数据)时,就会发生此错误。
示例
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.
在上面的示例中,foreach 循环在 studentsList 上执行。当学生的 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
广告