对于泛型列表的ForEach循环不断重复 [英] ForEach loop for a Generic List repeated endlessly

查看:97
本文介绍了对于泛型列表的ForEach循环不断重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之后反序列化一个只有一条记录的文件



似乎它处于一个不定式循环中

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

AddSerie 将无限地执行!

解决方案

如果我定义:

  //类级声明(在控制台应用程序中)
static List< string>串;

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中的字符串)
{
Loop(s);




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


After Deserializing a file with just one record

It seems that it's in an infinitive loop

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

AddSerie will be executed infinitively !

解决方案

If I define:

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

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

Then

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

executes normally, outputing a single string, while

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

loops indefinitely, adding '!'s in the process, and

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

throws an InvalidOperationException (Collection was modified; enumeration operation may not execute), which, in my opinion is the correct behavior. Why the List.ForEach method allows the list to be changed by the action, I do not know, but would like to find out :)

这篇关于对于泛型列表的ForEach循环不断重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆