详细报错:
InvalidOperationException: out of sync
System.Collections.Generic.Dictionary`2+Enumerator[System.String,System.Int32].VerifyState () (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:912)
System.Collections.Generic.Dictionary`2+Enumerator[System.String,System.Int32].MoveNext ()
定位到报错位置,是使用了字典(Dictionary),并且在遍历字典的时候更改了字典内容(删除,修改,添加)
private Dictionary<string, int> colorDict = new Dictionary<string, int> ();
foreach (var item in colorDict) {
if (item.Value == 1) {
colorDict [item.Key] = -1;
}
}
由于字典存储数据的特殊性,所以我们不能再遍历的时候修改数据,这样会导致内存数据异常。所以我将以上代码实现方式更改一下,先将需要修改的内容记录下来,然后在修改。
List<string> needChangeList = new List<string> ();
if (colorDict != null && colorDict.Count > 0) {
foreach (var item in colorDict) {
if (item.Value == 1) {
needChangeList.Add (item.Key);
}
}
}
if (needChangeList.Count > 0) {
foreach (var item in needChangeList) {
colorDict [item] = -1;
}
}
当我们更改字典,数组,堆栈,链表等数据结构的数据时,我们一定要思考该数据结构存储数据的方式,然后采用对应的方法更改数据,不然会造成很多异常。