收集被修改错误.NET2.0

时间:2014-02-08 16:41:58

标签: c# .net-2.0

基本上我有一个循环,应该从所有背包中删除黄金并添加回不同的数量,它会抛出一个集合被修改错误,显然它的工作方式在.NET 2.0中完全不同,任何人都可以给我一个手?

Type[] types = new Type[] { typeof( Gold ) };

int[] amounts = new int[] { 1 };

foreach( Item i8 in World.Items.Values )
{
    if( i8 is Container ) 
    { 
        Container c1 = (Container)i8; 
        int _Index = BackpackList.IndexOf(c1.Serial);
        if ( _Index>=0 )
        {
            amounts[0] = GoldOriginal[_Index];
            int NewAmount = GoldAmounts[_Index];

            if (c1!=null) { c1.ConsumeTotal( types, amounts ); }
            if (c1!=null && NewAmount>0) { c1.AddItem(new Gold(NewAmount)); }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

Type[] types = new Type[] { typeof( Gold ) };

int[] amounts = new int[] { 1 };

List<Item> items = new List<Item>(World.Items.Values);
foreach( Item i8 in items  )
{
    if( i8 is Container ) 
    { 
        Container c1 = (Container)i8; 
        int _Index = BackpackList.IndexOf(c1.Serial);
        if ( _Index>=0 )
        {
            amounts[0] = GoldOriginal[_Index];
            int NewAmount = GoldAmounts[_Index];

            if (c1!=null) { c1.ConsumeTotal( types, amounts ); }
            if (c1!=null && NewAmount>0) { c1.AddItem(new Gold(NewAmount)); }
        }
    }
}

此更改将防止错误。在迭代它时,更改将忽略World.Items的添加或删除。