【发布时间】:2018-09-03 17:51:48
【问题描述】:
我创建了一个问题池,从中选择随机问题来应用一些算法,无论如何,当我调试程序时,我得到 Index is outside the bounds of the array 错误。
要清楚我在说什么,这是我的问题:
首先我定义类 Gene 代表问题
public class Gene
{
public string question { get; set; }
public string CLO { get; set; }
public string type { get; set; }
public string Answer { get; set; }
public string mark { get; set; }
public string chapter { get; set; }
public Gene(string s, string t, string i, string a, string m, string c)
{
this.question = s;
this.type = t;
this.CLO = i;
this.Answer = a;
this.mark = m;
this.chapter = c;
}
}
List<Gene> QuestionList = new List<Gene>();
然后我从数据库中提出问题
protected void DropDownList5_SelectedIndexChanged(object sender, EventArgs e)
{
string sub = DropDownList5.Text;
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Sondos\Downloads\For the project\suz\ExamGenerationSystem.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
string s = "select * FROM QuestionBank WHERE (Cource_Code = '" + DropDownList5.SelectedItem.Text + "') ORDER BY RAND()";
SqlCommand cmd = new SqlCommand(s, con);
SqlDataReader dr;
con.Open();
dr = cmd.ExecuteReader();
dr.Read();
while (dr.Read())
{
string ques = dr["Question"].ToString();
string questype = dr["Question_Type"].ToString();
string quesCLO = dr["CLO"].ToString();
string quesAnswer = dr["Answer"].ToString();
string quesMark = dr["Mark"].ToString();
string quesChapter = dr["Chapter"].ToString();
QuestionList.Add(new Gene(ques, questype, quesCLO, quesAnswer, quesMark, quesChapter));
}
}
然后我提出问题池
Gene[] QuestionPool { get { return QuestionList.ToArray(); } }
当我尝试随机选择问题时:
private System.Random randome;
private Gene GetRandomQuestion()
{
int i = randome.Next(QuestionPool.Length);
return QuestionPool[i];
}
错误索引超出了数组的界限
return QuestionPool[i];
【问题讨论】:
-
也许有用,这是我之前的问题stackoverflow.com/questions/49448628/…
-
请编辑问题,只留下该问题的相关代码
-
仅供参考,您的代码很容易受到 SQL 注入攻击。使用参数化查询。
-
OT 每次访问 QuestionPool(获取长度或按索引访问一个值)时,您都在执行 .ToArray()
-
实际上有数百个关于此错误的问题。解决它的方法是调试,在该行下一个断点,看看发生了什么。