索引超出范围异常 [英] index out of range exception
问题描述
Hello All,
我有一个片段:
主题[] t = new 线程[ 3 ];
string [] items = new string [] { hi, hello, hey};
for ( int i = 0 ; i < = t.Length; i ++) /// 当我将鼠标悬停在此处时,我= 3
{
string s = items [i]; /// 索引超出范围异常抛出
t [i] = new 线程(()=> work(s));
t [i] .IsBackground = true ;
uplist< string> up = new uplist< string>(t [i]);
up.Add_item(items [i]);
}
这是否意味着当我说:
for(; i< = value;)///这里我被分配了值,所以在下一次迭代中我已达到最大值,因此它会爆发并抛出异常?
循环开始的那一刻抛出一个异常,因为当i = 3时应该抛出异常。
有人可以详细说明这个吗?
使用来自<$的索引迭代items
数组c $ c> t 数组。
如果他们都有相同数量的物品,那就有效,但这只是偶然。
更好地构造t
使用项目的长度
。
正确的代码是:
string [] items = new string [] { hi, hello, hey};
Thread [] t = new Thread [items.length];
for ( int i = 0 ; i < t.Length; i ++)
{
string s = items [i];
t [i] = new 主题(()= > work(s));
t [i] .IsBackground = true ;
uplist< string> up = new uplist< string>(t [i]);
up.Add_item(items [i]);
}
替换你的for循环
for ( int i = 0 ; i < t.Length; i ++) /// 当我将鼠标悬停在此处时,i = 3
{
string s = items [i]; /// 索引超出范围异常抛出
}
**因为尽管数组中有3个元素..但默认情况下数组从0位开始索引。因此,如果您尝试在第3个位置找到元素,则会出错。
for ( int i = 0 ; i < = t.Length; i ++)
将其替换为
for ( int i = 0 ; i < t.Length; i ++)
如果它是< =
它将检查3然后它将尝试访问数组的第四个索引,因此你得到索引异常..
Hello All,
I have a snippet :
Thread[] t = new Thread[3];
string[] items = new string[] {"hi","hello","hey"};
for(int i = 0 ; i <=t.Length; i++) /// When i hover my mouse here then i = 3
{
string s = items[i];/// index out of range exception thrown here
t[i] = new Thread(()=>work(s));
t[i].IsBackground = true;
uplist<string> up = new uplist<string>(t[i]);
up.Add_item(items[i]);
}
Does this mean that when i say :
for( ;i<=value;) ///here i is assigned the "value" and so in the next iteration i has reached the maximum value and hence it breaks out and throws an exception ?
The moment the loop starts it throws an exception, where as it should throw an exception when i = 3.
Can someone please elaborate on this?
You iterate over theitems
array using indices fromt
array.
If they both have the same number of items, that works, but it's only by chance.
Better constructt
using length ofitems
.
Correct code would be:
string[] items = new string[] {"hi","hello","hey"}; Thread[] t = new Thread[items.length]; for(int i = 0 ; i < t.Length; i++) { string s = items[i]; t[i] = new Thread(() => work(s)); t[i].IsBackground = true; uplist<string> up = new uplist<string>(t[i]); up.Add_item(items[i]); }
Replace your for loop by
for (int i = 0; i < t.Length; i++) /// When i hover my mouse here then i = 3 { string s = items[i];/// index out of range exception thrown here }
** Because though there are 3 elements in array.. but by default array starts indexing from 0 position. So if you try to find element at 3 rd position it is giving error.
for (int i = 0; i <= t.Length; i++)
replace it to
for (int i = 0; i < t.Length; i++)
if it is<=
it will check upto 3 then it will try to access the fourth index of the array, so you got the index exception..
这篇关于索引超出范围异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!