C# Dictionary修改遇到的一个错误 out of sync!

题目中问题是我批量修改字典的数据时遇到的问题,作为小白真是发现好多东西没有接触到啊。

上错误代码



        //foreach (KeyValuePair<string,float> item in dataDic)
        //{
           
        //    for (int i = 0; i < cars.Length; i++)
        //    {
        //        if (cars[i].name.Contains(item.Key))
        //        {
        //            dataDic[item.Value.ToString()] = cardatas[i].currentScore;
        //            break;
        //        }
        //    }          
        //}

错误提示

InvalidOperationException: out of sync
System.Collections.Generic.Dictionary`2+Enumerator[System.String,System.Single].VerifyState () (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:912)
System.Collections.Generic.Dictionary`2+Enumerator[System.String,System.Single].MoveNext () (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:835)
RaceData.Updatedatas () (at Assets/Scripts/Data/RaceData.cs:164)
RaceData.Update () (at Assets/Scripts/Data/RaceData.cs:80)

网上一顿搜集资料,说是不能用迭代去修改Dictionary,需要先把字典作为一个Buffer引出来,然后修改Buffer


上代码

        List<string> buffer = new List<string>(dataDic.Keys);
        foreach (string item in buffer)
        {
            for (int i = 0; i < cars.Length; i++)
            {
                if (cars[i].name.Contains(item))
                {
                    dataDic[item.ToString()] = cardatas[i].currentScore;
                    break;
                }
            }
        }

//这样就好使了,当然还有其他方法修改

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值