Unity3D -- C#之InvalidOperationException: out of sync

详细报错:

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

当我们更改字典,数组,堆栈,链表等数据结构的数据时,我们一定要思考该数据结构存储数据的方式,然后采用对应的方法更改数据,不然会造成很多异常。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值