自定义迭代器索引超出范围

时间:2014-03-04 15:32:47

标签: c# iterator

我正在为我的类分配制作一个自定义迭代器,我得到一个超出范围的索引,但我看不到在哪里。 当我调试它时,它会在最后一次迭代时停止(计数39,在索引39处停止)

我不确定迭代器中的问题仍然存在。

public override bool NextCourse(DataSet courseDS, DataView courseView, ref int currIndex)
{
    if (courseView.Count == 0)
        return false; 

    int nextIndex = currIndex + 1;


    if (nextIndex >= courseView.Count -1)
    {
        currIndex = nextIndex;
        return true;
    }

    if (currIndex < 0)
    {
        currIndex = 0;
        return true;
    }

    string currCourseNumber = (string)courseView[currIndex][(int)CourseListQueries.GetCourseListCols.CourseNumber];
    string courseNumber = String.Empty;

    currIndex++;

    do
    {
        courseNumber = (string)courseView[currIndex][(int)CourseListQueries.GetCourseListCols.CourseNumber];
        if ( String.Compare(courseNumber, currCourseNumber,true) != 0 ) 
            break;
        currIndex++;
    }
    while (currIndex < courseView.Count);

    return (currIndex < courseView.Count);
}// end NextCourse 

堆栈跟踪:

 Index 39 is either negative or above rows count.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IndexOutOfRangeException: Index 39 is either negative or above rows count.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:


[IndexOutOfRangeException: Index 39 is either negative or above rows count.]
   System.Data.DataView.GetRow(Int32 index) +5259337
   System.Data.DataView.get_Item(Int32 recordIndex) +12
   FIMS_Courses.Controls.CourseTable.GradTable.GradTable.InitializeControls(GenericContainer container) +4978
   Telerik.Sitefinity.Web.UI.SimpleView.CreateChildControls() +52
   System.Web.UI.Control.EnsureChildControls() +83
   System.Web.UI.Control.PreRenderRecursiveInternal() +42
   System.Web.UI.Control.PreRenderRecursiveInternal() +168
   System.Web.UI.Control.PreRenderRecursiveInternal() +168
   System.Web.UI.Control.PreRenderRecursiveInternal() +168
   System.Web.UI.Control.PreRenderRecursiveInternal() +168
   System.Web.UI.Control.PreRenderRecursiveInternal() +168
   System.Web.UI.Control.PreRenderRecursiveInternal() +168
   System.Web.UI.Control.PreRenderRecursiveInternal() +168
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +974

1 个答案:

答案 0 :(得分:1)

你似乎对最后一次迭代进行了检查,但它输出为true。 你是怎么称呼迭代器的?我假设它是一个while循环结构,因为它是一个bool类型。

我认为如果你做了这个改变就应该有效

if (nextIndex >= courseView.Count ) //to last element, yours is at second last.
    {
        currIndex = nextIndex;
        return false;// make it false, it should terminate and end loop . 
    }