2011-02-18 31 views
0

我有List和對象的字符串和雙打,我嘗試根據itemtype和它們的值調用不同的方法。在調試器中,我可以看到第一次迭代工作正常,但是在調用方法後第二次進入時出現錯誤。
如果我註釋掉這些方法並將其應用於一些簡單的方法,那麼我就會明白它與我如何調用這些方法有關。在對象foreach中調用方法時出錯

我該怎麼做,我該怎麼做才能使它工作?
如果有更簡單的方法來做我想要的,請讓我知道。

public double evaluateExpressionUsingVariableValues(List<Object> anExpression, Dictionary<String, double> variables) 
{ 
    foreach (object element in anExpression) 
    { 
     if(element.GetType()!=typeof(string)) 
     { 
      setOperand((double)element); 
     } 
     else if (element.GetType() == typeof(string)) 
     { 
      if (!element.ToString().StartsWith("%")) 
      performOperation((string)element); 
     else 
      setOperand(variables[element.ToString()]); 
     } 
    } 

     return this.operand; 
} 
+2

你能告訴你在哪一行哪個錯誤? – 2011-02-18 23:49:18

+2

拋出什麼異常?你確定列表中的所有對象都是字符串還是雙精度? – 2011-02-18 23:49:46

回答

1

如果您的方法(setOperand,performOperation)完全修改集合,您將得到一個異常。您在迭代時無法修改集合。一種方法是創建結果集合並在更改結果集時添加項目,而不是嘗試就地修改集合。

private void Foo() { 
    foreach(var item in items) { 
    if (item.IsBad) { 
     DeleteItem(item); // will throw an exception as it tries to modify items 
    } 
    } 
} 

private void DeleteItem(Item item) { 
    items.Remove(item); 
} 

相反,嘗試:

private void Foo() { 
    List<Item> result = new List<Item>(); 
    foreach(var item in items) { 
    if (!item.IsBad) { 
     result.Add(item); // we are adding to a collection other 
         // than the one we are iterating through 
    } 
    } 
    items = result; // we are no longer iterating, so we can modify 
        // this collection 
} 
0

您確定沒有任何方法正在調用集合(anExpression)?這種問題通常是由此造成的。嘗試用for循環替換foreach,看看你是否仍然遇到同樣的問題。

+0

謝謝,我不知道這一點。它實際上是在修改集合。將盡快改變它。這是我在這樣的論壇有史以來的第一篇文章,必須說它是真正有效的。再次感謝 – Cato 2011-02-19 03:19:27

相關問題