繁体   English   中英

数组索引超出范围

[英]Array Index Is Out of Bounds

我有这种方法可以根据其中的内容检查行。 我也有一个静态字符串数组,其中没有任何初始化。 我遇到了超出范围的索引错误,这对我来说没有任何意义,因为我在数组上没有最大长度。

这是我的方法:

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;
}

我认为您不需要该代码。 如果您只想显示独木舟和皮划艇的数量,则可以使用基本调用来选择

    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<string> listString = new List<string>();
   listString.Add("hi");
   listString.Add("bye");
   listString.Add("oh hai");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM