C#的Dictionary类型的值,知道key后,value可以修改吗?答案是肯定能修改的。我在遍历的过程中可以修改Value吗?答案是也是肯定能修改的,但是不能用For each循环。否则会报以下的Exception.
- System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'
之所以会报Exception是For each本身的问题,和Dictionary没关系。For each循环不能改变集合中各项的值,如果需要迭代并改变集合项中的值,请用For循环。
大家来看下例子:
- 1 // defined the Dictionary variable
- 2 Dictionary<int, string> td = new Dictionary<int, string>();
- 3 td.Add(1, "str1");
- 4 td.Add(2, "str2");
- 5 td.Add(3, "str3");
- 6 td.Add(4, "str4");
- 7 // test for
- 8 TestForDictionary(td);
- 9 // test for each
- 10 TestForEachDictionary(td);
- TestForDictionary Code
- 1 static void TestForDictionary(Dictionary<int, string> paramTd)
- 2 {
- 3
- 4 for (int i = 1;i<= paramTd.Keys.Count;i++)
- 5 {
- 6 paramTd[i] = "string" + i;
- 7 Console.WriteLine(paramTd[i]);
- 8 }
- 9 }
- TestForDictionary的执行结果
- string1
- string2
- string3
- string4
-
- TestForEachDictionary Code
- 1 static void TestForEachDictionary(Dictionary<int, string> paramTd)
- 2 {
- 3 int forEachCnt = 1;
- 4 foreach (KeyValuePair<int,string> item in paramTd)//System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'
- 5 {
- 6 paramTd[item.Key] = "forEach" + forEachCnt;
- 7 Console.WriteLine(paramTd[item.Key]);
- 8 forEachCnt += 1;
- 9 }
- 10 }
- TestForEachDictionary里的For each会在循环第二次的时候报错,也就是说它会在窗口中打印出“forEach1”后断掉。
-
-
-