繁体   English   中英

通用列表的ForEach循环不断重复

[英]ForEach loop for a Generic List repeated endlessly

Deserializing只有一条记录的文件后

似乎处于不定式循环中

IndexSeries = (List<string>)bFormatter.Deserialize(fsSeriesIndexGet);
IndexSeries.ForEach(name => AddSerie(name));
//IndexSeries.ForEach(delegate(String name)
//{
      //    AddSerie(name);
//});

AddSerie将无限执行!

您使用不明确的用语。 首先,您提到一个无限循环,然后提到AddSerie将“无限地”执行。 基于此,我认为您提出的问题不是ForEach持续不断(隐含/陈述),而是AddSerie做的事情似乎永远存在。

这甚至可能相当于乔伊提到的某些东西:如果你同时的范围内添加元素到列表ForEach通话,然后在你完成你总是落后一步,因此将不“完整”。 但是, 如果AddSerie除了执行其他操作, 实际上会相对较快地发生OutOfMemoryException 如果 AddSerie是一种相对耗时的方法,则可能需要更长的时间才能达到目标。 再说一次, 如果 AddSerieAddSerie年龄来完成而不增加列表的长度,那么您可能永远也不会遇到这样的异常(在所讨论的上下文中)。

显示您的AddSerie代码可能对确定实际问题最有帮助。

如果我定义:

//class level declaration (in a console app)
static List<string> strings;

static void Loop(string s)
{
  Console.WriteLine(s);
  strings.Add(s + "!");
}

然后

static void Main(string[] args)
{
  strings = new List<string> { "sample" };
  strings.ForEach(s => Console.WriteLine(s));
}

正常执行,输出单个字符串,而

static void Main(string[] args)
{
  strings = new List<string> { "sample" };
  strings.ForEach(s => Loop(s));
}

无限循环,在此过程中添加“!”,然后

static void Main(string[] args)
{
  strings = new List<string> { "sample" };
  foreach (string s in strings)
  {
    Loop(s);
  }
}

抛出InvalidOperationException( 集合已被修改;枚举操作可能不会执行 ),在我看来这是正确的行为。 为什么List.ForEach方法允许通过操作更改列表,我不知道,但想知道:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM