队列ForEach循环投掷出现InvalidOperationException队列、ForEach、InvalidOperationException

由网友(帅死鬼i)分享简介:我没有用队列< T> 来任何真正的程度之前,所以我可能会丢失一些东西明显。我想遍历问答LT; EnemyUserControl> 这样的(每帧):I haven't used Queues to any real degree before, so I might be missing som...

我没有用队列< T> 来任何真正的程度之前,所以我可能会丢失一些东西明显。我想遍历问答LT; EnemyUserControl> 这样的(每帧):

I haven't used Queues<T> to any real degree before, so I might be missing something obvious. I'm trying to iterate through a Queue<EnemyUserControl> like this (every frame):

foreach (var e in qEnemy)
{
     //enemy AI code
}

当敌人死,敌人的用户控件引发我订阅了一个事件,我这样做(在队列中的第一个敌人是通过设计删除):

When an enemy dies, the enemy user control raises an event I've subscribed to and I do this (the first enemy in the queue is removed by design):

void Enemy_Killed(object sender, EventArgs e)
{      
     qEnemy.Dequeue();

     //Added TrimExcess to check if the error was caused by NULL values in the Queue (it wasn't :))
     qEnemy.TrimExcess();
}

不过,出列方法被调用后,我得到一个 InvalidOperationException异常的foreach 循环。当我使用皮克相反,有那么它必须做一些与队列本身的变化,因为出列删除的对象都没有错误。 我最初的猜测是,它的抱怨,我修改正在被重复的枚举器的集合,但出队被循环外进行的?

However, after the Dequeue method is called, I get an InvalidOperationException on the foreach loop. When I use Peek instead, there are no errors so it has to do something with the changing of the Queue itself since Dequeue removes the object. My initial guess is that it's complaining that I'm modifying a collection which is being iterated by the Enumerator, but the dequeuing is being performed outside the loop?

任何想法可能会造成这个问题?

Any ideas what could be causing this issue?

感谢

推荐答案

正在修改的foreach 循环内的队列。这是什么原因造成的除外。 简体code证明了这个问题:

You are modifying queue inside of foreach loop. This is what causes the exception. Simplified code to demonstrate the issue:

var queue = new Queue<int>();
queue.Enqueue(1);
queue.Enqueue(2);

foreach (var i in queue)
{
    queue.Dequeue();
}

可能的解决方案是增加了ToList(),像这样的:

foreach (var i in queue.ToList())
{
    queue.Dequeue();
}
阅读全文

相关推荐

最新文章