索引超出了数组的范围 [英] Index is outside the bound of array

查看:88
本文介绍了索引超出了数组的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,





我在c#中声明了一个空字符串数组,我试图用一些值填充它。但每次它都说索引超出了数组的范围。当然这意味着我试图插入的值越过数组。但我无法在我的代码中找到错误。需要一些帮助。

这是我的代码:



 string [] week = new string [0]; 
int loop = 14;

for(int i = 1; i< = loop; i ++)
{
weekNo = i + 10;
周[i-1] = weekNo.ToString(); //此行有错误
}





我尝试过:



我尝试用其他方式声明数组

 string [] week = new string [0]; 
string [] week = new string [] {};
string [] week = new string [0] {};
string [] week = new string [0] {};



但它说同样的错误。

解决方案

声明数组时,您可以准确指定它可以包含的元素数,并且该数字永远不会更改。它不能上去,它不能下去。所以当你这样说:

  string  [] week =  new   string  [ 0 ]; 

您声明一个变量名为week的周,它包含对数组的引用,该数组可以保存零字符串。这意味着任何索引值都将自动超出数组的范围。

如果您知道要存储多少项,请在定义中使用它:

< pre lang =c#> int loop = 14 ;
string [] week = new string < /跨度> [循环];

for int i = 1 ; i< = loop; i ++)
{
int weekNo = i + 10;
周[i-1] = weekNo.ToString();
}

如果你不这样做,那就不要使用数组,使用List< T>:

 List< ;串GT; week =  new 列表< string>(); 
int loop = 14 ;
for int i = 1 ; i< = loop; i ++)
{
int weekNo = i + 10;
week.Add(weekNo.ToString());
}

如果需要,您可以随后在集合上使用索引来访问单个元素。


Hi Everyone,


I have declared an empty string array in c# and I am trying to fill it with some values. But each time it says 'index is outside the bound of array'. Of course it means that the value I am trying to insert is getting outside the array. But I am not able to find the fault in my code. Need some help.
Here is my code:

string[] week = new string[0];
int loop=14;

for(int i=1;i<=loop;i++)
   {
     weekNo=i+10;
     week[i-1]=weekNo.ToString(); //this line has error
}



What I have tried:

I tried declaring the array in other ways

string[] week = new string[0];
string[] week = new string[]{};
string[] week = new string[0]{};
string[] week = new string[0] {};


But it says same error.

解决方案

When you declare an array, you specify exactly how many elements it can contain, and that number can never change. It can't go up, it can't go down. So when you say this:

string[] week = new string[0];

You declare a variable called week which contains a reference to a array which can holed zero strings. That means that any index value will automatically be outside the bounds of the array.
If you know how many items you want to store, use that in the definition:

int loop=14;
string[] week = new string[loop];
 
for(int i=1;i<=loop;i++)
   {
   int weekNo=i+10;
   week[i-1]=weekNo.ToString(); 
   }

If you don't, then don;t use an array, use a List<T>:

List<string> week = new List<string>();
int loop=14;
for(int i=1;i<=loop;i++)
   {
   int weekNo=i+10;
   week.Add(weekNo.ToString());
   }

You can subsequently use indexing on the collection to access individual elements, if you need to.


这篇关于索引超出了数组的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆