我试图实现一个片段,我们可以循环遍历动态的对象列表。
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var l = new List<int>();
l.Add(1);
l.Add(2);
l.Add(3);
l.Add(4);
foreach(var i in l){
Console.WriteLine(i);
if(i==3){
l.Add(5);
}
}
}
}
这会导致运行时错误。
1
2
3
Run-time exception (line 15): Collection was modified; enumeration operation may not execute.
Stack Trace:
[System.InvalidOperationException: Collection was modified; enumeration operation may not execute.]
at Program.Main(): line 15
感谢任何帮助。感谢。
答案 0 :(得分:2)
这可以通过将foreach
替换为for
循环
for (var i = 0; i < l.Count; i++)
{
Console.WriteLine(l[i]);
if (l[i] == 3)
{
l.Add(5);
}
}