【问题标题】:Looping through a dynamic List of objects [duplicate]循环遍历对象的动态列表[重复]
【发布时间】:2017-01-23 22:29:39
【问题描述】:

我正在尝试实现一个 sn-p,我们可以在其中循环遍历对象的动态列表。

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

感谢任何帮助。谢谢。

【问题讨论】:

    标签: c# .net


    【解决方案1】:

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

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

    【讨论】:

    • 我认为你需要有if(l[i] == 3) 以保持与OP相同的含义。
    • 我错过了@StriplingWarrior。已更正。
    • 谢谢@StriplingWarrior 和 Reddy
    猜你喜欢
    • 2021-10-05
    • 2020-03-30
    • 1970-01-01
    • 2018-09-26
    • 2016-07-08
    • 2015-03-18
    • 2015-05-16
    • 2010-10-22
    • 1970-01-01
    相关资源
    最近更新 更多