2014-02-08 50 views
0

本質上我有一個循環,應該從所有的揹包中刪除黃金,並添加一個不同的金額,它會拋出一個集合被修改錯誤,顯然它的工作方式在.NET中完全不同2.0,有誰能幫我一下嗎?集合被修改錯誤.NET2.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)); } 
     } 
    } 
} 
+0

你能粘貼這個ConsumeTotal方法的代碼嗎? –

+0

您可能在該foreach循環中調用的方法中修改了World.Items.Values,但是如果沒有更多的代碼就很難說。 – Dirk

回答

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的添加或刪除操作。

+0

Linq在.NET 2.0中不存在 – user3287662

+0

Duh! (拍額)。我編輯了代碼 - 現在應該工作。 –