【问题标题】:Index was outside the bounds of the array when use random c#使用随机 c# 时索引超出数组范围
【发布时间】: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()
  • 实际上有数百个关于此错误的问题。解决它的方法是调试,在该行下一个断点,看看发生了什么。

标签: c# arrays list random


【解决方案1】:

int i = randome.Next(QuestionPool.Length);

这里如果QuestionPool 为空,则变为int i = randome.Next(0),返回零。 因此,

返回问题池[i]; // 其中 i 变为 0

将抛出 Index was outside the bounds,因为 QuestionPool 为空且索引 0 处没有任何内容。

所以请确保 QuestionPool 不为空。


会导致QuestionPool为空的一些情况。

  1. Cource_Code = DropDownList5.SelectedItem.Text 的数据库中没有记录 在这种情况下,while (dr.Read()) 将在第一次迭代时为 false,并且不会将 Gene 添加到 QuestionList
  2. 在将任何Gene 添加到QuestionList 之前调用GetRandomQuestion

避免 SQL 注入

此行易受 SQL 注入攻击

(Cource_Code = '" + DropDownList5.SelectedItem.Text + "')

这意味着如果用户将 SelectedItem 的文本更改为类似

a'); Drop table QuestionBank; -- //Anything after -- becomes a comment

那么查询就会变成

select * FROM QuestionBank WHERE (Cource_Code = 'a'); Drop table QuestionBank;

你的桌子将被丢弃。

为避免这种情况,请参阅answer


以数组形式列出

当您有列表时,您还可以通过索引访问其项目。要获得它的长度,您可以使用 Count。因此,GetRandomQuestion 可以变成

private Gene GetRandomQuestion()
{
    int i = randome.Next(QuestionList.Count);
    return QuestionList[i];
}

而且您不需要 QuestionPool,前提是您仅将其用于此目的。

【讨论】:

  • 如何检查 QuestionPool 是否为空。?如果有人可以在其余代码中看到错误,我会放置所有相关代码。
  • @Sondos 您使用的是哪个开发环境?视觉工作室?
  • 在 Visual Studio 中,您从 03:00 开始通过调试器 youtube.com/watch?v=u-HdLtqEOog 检查值。我可以在这里解释它,但我相信它在那里解释得非常好和详细。版本可能不同,但并不重要。关于问题池可能为空的地方,请查看我更新的答案。
【解决方案2】:

您只是在引用之前错过了实例化 random

private System.Random randome;
private Gene GetRandomQuestion()
{
    randome = new System.Random  // here
    int i = randome.Next(QuestionPool.Length);
    return QuestionPool[i];
}

【讨论】:

  • 那么会有一个 NullReference 异常,而不是索引超出范围
  • @HansKesting 是的。但是上面的代码应该抛出 NullReferenceException 而不是 index out of bounds。
猜你喜欢
  • 1970-01-01
  • 2021-06-20
  • 2013-08-12
  • 2014-09-09
  • 1970-01-01
  • 2016-03-29
  • 2020-04-26
  • 2019-12-17
  • 2020-04-10
相关资源
最近更新 更多