為什麼會出現“集合已修改;列舉操作可能無法執行”錯誤,以及如何在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP