开发者

Error when calling a method in foreach with object

I have List with objects of strings and doubles, and I try to call different methods based on the itemtype and the开发者_StackOverflow中文版ir value. In the debugger I can see that the first iteration works fine, but an error shows when entering the second time after a method is called.

If i comment out the methods and put in simple methods it works, so I understand that it something with how I call the methods.

What do I do wrong, and what can I do to make it work?

If there is easier ways to do what I'm trying, please let me know.

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


If your methods (setOperand, performOperation) modify the collection at all, you will get an exception. You can't modify the collection while you are iterating over it. One method is to create a result collection and add items to it as you change them, rather than trying to modify the collection in-place.

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

Instead, try:

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
}


Are you sure that none of the methods you are calling is modifying the collection (anExpression) ? This kind of problem is often the result of that. Try replacing the foreach by a for loop and see if you still get the same issue.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜