简体   繁体   English

如何删除异常System.InvalidOperationException?

[英]how to remove the exception, System.InvalidOperationException?

code is given below 代码如下

Queue<int> queXpTrackerX = new Queue<int>(10);
Queue<int> queXpTrackerY = new Queue<int>(10);       

if (iCounterForXpTrack < 10)
{
    queXpTrackerX.Enqueue(X);
    queXpTrackerY.Enqueue(Y);
    iCounterForXpTrack++;
}//End IF
else
{
    queXpTrackerX.Dequeue();
    queXpTrackerY.Dequeue();
    queXpTrackerX.Enqueue(X);
    queXpTrackerY.Enqueue(Y);
}//End else

for (int indexXp = 0; indexXp < iCounterForXpTrack; indexXp++)
{
    gXpTracker.DrawEllipse(Pens.Cyan, queXpTrackerX.ElementAt(indexXp) , queXpTrackerY.ElementAt(indexXp), 5, 5);
}//end for

I suspect that the most likely cause for you InvalidOperationException is trying to Dequeue from a queue when it is empty. 我怀疑最可能导致您InvalidOperationException的原因是尝试从队列为空时使其出队。 Did you have the exception message? 您有异常消息吗? Is it 'Queue empty.'? 是“队列为空”吗?

This can happen if your iCounterForXpTrack becomes out of sync with the number of elements in the queue. 如果您的iCounterForXpTrack与队列中的元素数量不同步,则会发生这种情况。 It would be better to just ask the queue directly to avoid this possible error: 最好直接询问队列以避免这种可能的错误:

    if (queXpTrackerX.Count < 10)
    {
        queXpTrackerX.Enqueue(X);
        queXpTrackerY.Enqueue(Y);
    }
    else
    {
        queXpTrackerX.Dequeue();
        queXpTrackerY.Dequeue();
        queXpTrackerX.Enqueue(X);
        queXpTrackerY.Enqueue(Y);
    }

A possible reason that your code fails is if you initialized iCounterForXpTrack to 10 thinking that new Queue<int>(10) creates a queue that starts with 10 elements. 代码失败的可能原因是,如果您将iCounterForXpTrack初始化为10,并认为new Queue<int>(10)创建了一个以10个元素开头的队列。 This is not the case. 不是这种情况。 The queue is initially empty. 队列最初是空的。 Providing the capacity to the queue constructor is just a performance optimization and is not strictly needed. 向队列构造函数提供容量仅仅是性能优化,并非严格要求。

Another issue with your code: instead of having two queues, one for x and one for y, you should use some sort of Point class and a Queue<Point> . 代码的另一个问题:不要使用两个队列,一个用于x,一个用于y,而应该使用某种Point类和一个Queue<Point> This simplifies the code and eliminates possible errors from the two queues becoming out of sync. 这简化了代码,并消除了两个队列不同步的可能错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM