簡體   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