数组索引越界

本文关键字:越界 索引 数组 | 更新日期: 2023-09-27 18:17:35

我有这个方法,根据它的内容检查一行。我还有一个静态字符串数组,初始化时没有任何内容。我得到了一个越界的索引错误这对我来说毫无意义因为我没有设置数组的最大长度。

这是我的方法:

private void PrintTable(DataTable table)
{ 
    foreach (DataRow row in table.Rows)
    {
        litCanCount.Text = "Canoe count is: ";
        litKayCount.Text = "Kayak count is: ";
        string currRow = row["CraftType"].ToString();
        if (currRow == CANOE)
        {
            Response.Write("CANOE INCREMENT!<br />");
            CANOEi++;
            txtCanCount.Text = CANOEi.ToString();
            arr[i] = currRow;
            i++;
        }
        if (currRow == KAYAK)
        {
            Response.Write("KAYAK INCREMENT!<br />");
            KAYAKi++;
            txtKayCount.Text = KAYAKi.ToString();
            arr[i] = currRow;
            i++;
        }
        for (int a = 0; arr.Length > a; a++)
        {
            Response.Write(arr[a] + "<br />");
        }
    }
}

这是我的类的顶部,我的静态变量:

public partial class Index: System.Web.UI.Page
{
    string CANOE = "Canoe";
    string KAYAK = "Kayak";
    int CANOEi;
    int KAYAKi;
    string[] arr = new string[] { };
    int i = 0;
}

数组索引越界

我认为您不需要这些代码。如果您只想显示独木舟和皮艇的计数,您可以使用Select

的基本调用。
    DataRow[] canoe = table.Select("CraftType = 'Canoe'");
    DataRow[] kayak = table.Select("CraftType = 'Kayak'");
    litCanCount.Text = "Canoe count is: " + canoe.Length;
    litKayCount.Text = "Kayak count is: " + kayak.Length;

如果你仔细想想,数据表只是一个复杂的数组,框架提供了许多方法来处理数据表。

例如,在LINQ

int canoeNumber = table.AsEnumerable().Count(x => x["CraftType"].ToString() == "Canoe");

数组必须指定长度

数组长度为零(运行时异常)

static void Main()
{
    string[] arr = new string[] { }; //Array with no length
    arr[0] = "hi"; //Runtime exception
}

单长度数组(无例外)

static void Main()
{
    string[] arr = new string[1]; //Array with one length, index starts at zero
    arr[0] = "test";
}

如果你想使用集合而不定义大小,那么考虑使用list

List Collection(不需要定义长度)

   List<string> listString = new List<string>();
   listString.Add("hi");
   listString.Add("bye");
   listString.Add("oh hai");