C#的Dictionary類型的值,知道key後,value可以修改嗎?答案是肯定能修改的。我在遍歷的過程中可以修改Value嗎?答案是也是肯定能修改的,但是不能用For each迴圈。否則會報以下的Exception. 之所以會報Exception是For each本身的問題,和Dictionar ...
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”後斷掉。