ArrayList尝试访问一个索引的次数过多
本文关键字:索引 一个 访问 ArrayList | 更新日期: 2023-09-27 17:58:13
我在下面的代码中遇到了一个错误,因为我的计数器将自己增加了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++;
}
}
如果我使用counter < wordList.Count -1)
,它不会给我错误,但也不会加载列表中的最后一个单词。我做错了什么?
错误:
An exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll but was not handled in user code
Additional information: Index was out of range. Must be non-negative and less than the size of the collection.
您可以这样更改代码:
if (counter < wordList.Count)
{
object o = wordList[counter++];
LabelWord.Text = o.ToString();
}
这不会给您OufOfRange
异常,并且应该返回所有项目。
如果
if (counter < wordList.Count)
{
counter++;
}
假设count
是10
该列表是从0到9的索引
在计数器为9的最后一个循环中。。。条件为真,它增加1,并终止循环
i case 2 if (counter < wordList.Count-1)
it correct,,increments until 8 and terminate
使用这个
if (counter <=wordList.Count-1
)