使用对象调用 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;
}
I have List with objects of strings and doubles, and I try to call different methods based on the itemtype and their 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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的方法(
setOperand
、performOperation
)完全修改了集合,您将收到异常。在迭代集合时无法修改集合。一种方法是创建结果集合并在更改项目时向其中添加项目,而不是尝试就地修改集合。相反,请尝试:
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.Instead, try:
您确定您调用的方法都没有修改集合(anExpression)吗?此类问题往往就是由此造成的。尝试用 for 循环替换 foreach ,看看是否仍然遇到相同的问题。
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.