【问题标题】:Why can't I .add a Dictionary(Key, Value) in a foreach?为什么我不能在 foreach 中添加 Dictionary(Key, Value)?
【发布时间】:2010-09-30 02:04:58
【问题描述】:

如果我想遍历 Dictionary(Key, Value)... 为什么不能在循环中添加新的键值对?

Dictionary<string, string> persons = new Dictionary<string, string>();

persons.Add("roger", "12");
persons.Add("mary", "13");

foreach (KeyValuePair<string,string> person in persons)
{
 Console.WriteLine("Name: " + person.Key + ", Age: " + person.Value);
 persons.Add("Xico", "22");
}

【问题讨论】:

    标签: c# dictionary foreach


    【解决方案1】:

    这是因为枚举器的构造方式。

    来自 MSDN Dictionary.Enumerator

    只要集合保持不变,枚举数就保持有效。如果对集合进行了更改,例如添加、修改或删除元素,则枚举器将不可恢复地失效,并且其行为未定义。

    不过,解决这个问题很容易。只需复制字典(或它的键)并遍历它,添加/删除/等。根据需要从原始字典中提取。

    【讨论】:

      【解决方案2】:

      枚举时不能修改字典,就这么简单。否则你什么时候知道你已经完成了?

      【讨论】:

        【解决方案3】:

        如果您想这样做,您应该获取 Dictionary 对象的副本(可以通过多种方式完成)然后枚举它,将您想要的内容添加到原始对象中。

        只是在枚举字典时不能添加新项目。

        【讨论】:

          【解决方案4】:

          在枚举集合时(即 foreach 循环),无法从集合中添加或删除项目。想想如果允许的话会带来的所有问题。

          【讨论】:

            【解决方案5】:

            这只是……奇怪。您正尝试为字典中已有的每个人再次添加同一个人。

            另外:为什么将年龄存储为字符串? int(甚至 DateTime)似乎更合适。

            【讨论】:

              【解决方案6】:

              因为它会更改您正在滚动的词典中的项目... 它没有任何意义......(你可能会永远循环)

              【讨论】:

                【解决方案7】:

                您试图在迭代循环时更改集合中的条目数。 for 循环可以完成此操作,但 foreach 迭代器不允许您这样做。

                【讨论】:

                  【解决方案8】:
                  Dictionary<string, string> persons = new Dictionary<string, string>();
                  persons.Add("roger", "12");
                  persons.Add("mary", "13");
                  for (int i = 0; i < persons.Count; i++){ 
                  Console.WriteLine("Name: " + persons[i].Key + ", Age: " + persons[i].Value); 
                  persons.Add("Xico", "22");
                  }
                  

                  请注意,这是一个无限循环,因为您总是在到达最后一个条目之前添加一个人。

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 2012-01-10
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2015-10-16
                    • 2011-10-25
                    • 1970-01-01
                    相关资源
                    最近更新 更多