C# 使用随机c时,索引超出了数组的边界#
我创建了一个问题池,从中我选择随机问题来应用一些算法,不管怎样,当我调试程序时,我得到的索引超出了数组错误的界限 为了清楚地了解我在说什么,下面是我的课堂提问: 首先定义了类基因表示问题C# 使用随机c时,索引超出了数组的边界#,c#,arrays,list,random,C#,Arrays,List,Random,我创建了一个问题池,从中我选择随机问题来应用一些算法,不管怎样,当我调试程序时,我得到的索引超出了数组错误的界限 为了清楚地了解我在说什么,下面是我的课堂提问: 首先定义了类基因表示问题 public class Gene { public string question { get; set; } public string CLO { get; set; } public string type { get; set; } public string Answ
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>();
然后我把问题集中起来
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];
在引用它之前,您刚刚错过了实例化随机
private System.Random randome;
private Gene GetRandomQuestion()
{
randome = new System.Random // here
int i = randome.Next(QuestionPool.Length);
return QuestionPool[i];
}
int i=random.Next(QuestionPool.Length)
这里,如果QuestionPool
为空,则该值变为inti=randome.Next(0)
,返回零。
所以,
返回问题库[i];//我变成0的地方
Will throw索引超出了范围
,因为QuestionPool为空,索引0处没有任何内容
因此,请确保问题库不是空的
某些情况会导致
问题库
为空
Cource\u code=DropDownList5的记录。请选择editem.Text
在这种情况下,while(dr.Read())
将在第一次迭代时为false
,并且没有基因
将添加到问题列表中
基因
添加到问题列表
避免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;
你的桌子会掉下来的
为了避免这种情况,请参考此
以数组形式列出 当您有列表时,还可以通过索引访问其项。要得到它的长度,可以使用Count。因此,这个问题可以成为
private Gene GetRandomQuestion()
{
int i = randome.Next(QuestionList.Count);
return QuestionList[i];
}
您不需要问题库,前提是您仅用于此目的。可能有用,这是我的上一个问题,请编辑问题以仅留下此问题的相关代码。仅供参考,您的代码可能会受到SQL注入攻击。使用parameterized queries.OT每次访问该问题库(获取长度或通过索引访问一个值)时,您都在执行.ToArray()命令,关于此错误,实际上有数百个问题。解决这个问题的方法是调试,在那一行上放置一个断点,然后看看发生了什么。然后会出现一个NullReference异常,而不是索引超出范围bounds@HansKesting对但是上面的代码应该抛出NullReferenceException而不是索引越界。如何检查问题池是否为空。?如果有人能在代码的其余部分看到错误,我会放上所有相关的代码。@Sondos您使用的是哪种开发环境?Visual Studio?在Visual Studio中,从03:00开始通过调试器检查值。我可以在这里解释,但我相信那里的解释非常好,非常详细。版本可能不同,但没什么关系。关于问题库可能为空的位置,请检查我的更新答案。
private Gene GetRandomQuestion()
{
int i = randome.Next(QuestionList.Count);
return QuestionList[i];
}