我的C#程序有问题:我创建了一个包含10个问题和10个图像的测验.我得到这个Length cannot be less than zero.\r\nParameter name: length在线路
int imageIndex = int.Parse(line.Substring(0, delimiter));
Run Code Online (Sandbox Code Playgroud)
即使在我的记事本文件中,我也包含了图像索引:
3:What is the foo in the bar?
10:How can you add a widget?
4:Why pick a bar over a foo?
Run Code Online (Sandbox Code Playgroud)
这是代码:
if (nr >= questions.Count)
{
button1.Enabled = false;
}
else
{
Random r = new Random();
int x;
do
{
x = r.Next(questions.Count);
}
while (questions[x].displayed == true);
textBox1.Text = questionText;
radioButton1.Text = questions[x].answer1;
radioButton2.Text = questions[x].answer2;
questions[x].displayed= true;
current_question = x;
}
Run Code Online (Sandbox Code Playgroud)
你以前有这样一条线:
int delimiter = line.IndexOf(':');
Run Code Online (Sandbox Code Playgroud)
...但是你没有检查返回值.如果它是-1,那意味着在该特定行中找不到分隔符 - 但Substring无论如何你都要将它传递给它.检查的价值delimiter在使用它之前-这样你可以抛出一个更有用的异常(或跳过线,或任何你想做的事).
我真的建议你显著改变你的代码-而不是保持questions一个List<string>或不管它是什么,我想创建一个Question类.在阅读文本时解析文本行,在此时丢弃失败 - 或抛出异常 - 而不是等到碰巧遇到错误的问题.然后,您可以List<Question>使用其他代码使其余代码更简单.
你可能也想保持Queue<Question>其最初的完整列表,洗牌的副本.如果要显示新问题,只需从该队列中获取下一个元素即可.这样,当您选择已经显示的问题时,您将不需要循环.(你可能希望在课堂上包含一个Index或一个QuestionNumber属性Question,大概是......)
请注意,它可能适用于您真正了解的所有行,但您的文件末尾有一些空行.你可能只想跳过空行.