C# ArrayList试图访问一个索引的次数过多

C# ArrayList试图访问一个索引的次数过多,c#,arraylist,C#,Arraylist,我在下面的代码中得到一个错误,因为我的计数器自身增加了1倍太多,我不明白为什么 代码: ...private static int counter = 0; protected void ButtonSubmit_Click(object sender, EventArgs e) { SendWord(); object o = wordList[counter]; LabelWord.Text = o.T

我在下面的代码中得到一个错误,因为我的计数器自身增加了1倍太多,我不明白为什么

代码:

...private static int counter = 0;

protected void ButtonSubmit_Click(object sender, EventArgs e)
        {
            SendWord();
            object o = wordList[counter];
            LabelWord.Text = o.ToString();
            if (counter < wordList.Count)
            {
                counter++;
            }
         }

您可以按如下方式更改代码:

if (counter < wordList.Count)
{
    object o = wordList[counter++];
    LabelWord.Text = o.ToString();
}
if(计数器

这不会给您带来异常,应该返回所有项目。

如果

 if (counter < wordList.Count)
            {
                counter++;
            }
if(计数器
假设
count
是10

该列表的索引范围为0到9

在最后一个循环中,当计数器为9时…条件为真,它增加1,并终止循环

案例2
if(counter
it correct,,,递增到8,然后终止

用这个


if(counter)尝试使用
counter我已经尝试过了,需要更多的上下文。
wordList
的内容在哪里发生了变化?另外,为什么要使用
ArrayList
而不是
List
?您仍然需要包含
对象o=wordList[counter++];
语句在IF块内,或者在
计数器==wordList.Count时可能遇到超出范围的异常
 if (counter < wordList.Count)
            {
                counter++;
            }