2016-09-15 62 views
0

我试图实现一个片段,我们可以通过动态列表对象进行循环。通过动态列表循环对象列表

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 

任何帮助表示赞赏。谢谢。

回答

2

这可以通过for循环替换foreach实现

for (var i = 0; i < l.Count; i++) 
{ 
    Console.WriteLine(l[i]); 
    if (l[i] == 3) 
    { 
     l.Add(5); 
    } 
} 
+0

https://dotnetfiddle.net/f6gawa – Reddy

+1

我认为你需要有'如果(L [I] == 3)'保持与OP的含义相同。 – StriplingWarrior

+0

我错过了@StriplingWarrior。纠正。 – Reddy