为什么我不能在foreach中添加字典(键,值)? [英] Why can't I .add a Dictionary(Key, Value) in a foreach?

查看:41
本文介绍了为什么我不能在foreach中添加字典(键,值)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我要遍历Dictionary(Key,Value)...为什么不能在循环中添加新的key-value对?

If I want to loop over a Dictionary(Key, Value)... why cant I add a new key-value pair in the loop?

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");
}

推荐答案

如果要执行此操作,则应获取字典对象的副本(可以用多种方法完成),然后将其枚举,然后将其添加到原始的.

If you want to do this you should get a copy of the Dictionary Object (can be done in many ways) then enumerate it, add what you want to the original.

简而言之,您无法在枚举字典时添加新项目.

Simply you can't add new items while enumerating an Dictionary.

这篇关于为什么我不能在foreach中添加字典(键,值)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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