Skip to main content
 首页 » 编程设计

c#之索引数组超出范围异常

2024年02月20日15telwanggs

我尝试将 SQL 结果保存在数组中并将其返回。但我遇到了一个异常(exception):数组超出范围错误。

这是我的代码:

 public BookingUpdate[] getBookingUpdates(string token) 
{ 
    String command = "SELECT b.ID,b.VERANSTALTER, rr.VON ,rr.BIS, b.THEMA, b.STORNO, ra.BEZEICHNUNG from BUCHUNG b JOIN RESERVIERUNGRAUM rr on rr.BUCHUNG_ID = b.ID JOIN RAUM ra on ra.ID = rr.RAUM_ID WHERE b.UPDATE_DATE BETWEEN DATEADD (DAY , -20 , getdate()) AND getdate() AND b.BOOKVERNR = 0"; 
    SqlConnection connection = new SqlConnection(GetConnectionString()); 
    BookingUpdate[] bookingupdate = new BookingUpdate[1]; 
    connection.Open(); 
    try 
    { 
        SqlCommand cmd = new SqlCommand(command, connection); 
        SqlDataReader rdr = null; 
        int count = 0; 
        rdr = cmd.ExecuteReader(); 
 
 
            while (rdr.Read()) 
            { 
                DataTable dt = new DataTable(); 
                dt.Load(rdr); 
                count = dt.Rows.Count; 
                for (int c = 0; c < count; c++) 
                { 
                    bookingupdate = new BookingUpdate[c]; 
                    bookingupdate[c].bookingID = (long)rdr["ID"]; // <---- Error is here 
                    bookingupdate[c].fullUserName = rdr["VERANSTALTER"].ToString(); 
                    bookingupdate[c].newStart = (DateTime)rdr["VON"]; 
                    bookingupdate[c].newStart = (DateTime)rdr["BIS"]; 
                    bookingupdate[c].newSubject = rdr["THEMA"].ToString(); 
                    bookingupdate[c].newlocation = rdr["BEZEICHNUNG"].ToString(); 
                    if (rdr["STORNO"].ToString() != null) 
                    { 
                        bookingupdate[c].deleted = true; 
                    } 
                    else 
                    { 
                        bookingupdate[c].deleted = false; 
                    } 
 
                } 
 
            } 
 
    } 
 
    catch (Exception ex) 
    { 
        log.Error(ex.Message + "\n\rStackTrace:\n\r" + ex.StackTrace); 
    } 
    finally 
    { 
        connection.Close(); 
    } 
    return bookingupdate; 
} 

我错过了什么?

请您参考如下方法:

bookingupdate = new BookingUpdate[c]; 
bookingupdate[c].bookingID = (long)rdr["ID"];  

您正在创建一个长度为 c 的数组,这意味着它具有索引 0 到 (c-1) - 然后您在尝试时超出范围存储在位置c。