C#随机抽取题库题目时触发Index was outside the bounds of the array错误
Hey there! Let's work through that frustrating array index error you're hitting when pulling random questions from your question bank. Given you've got a Gene class representing each question, here are the most common causes and fixes tailored to your scenario:
1. Your question bank array/collection is empty or uninitialized
If your Gene array (say something like Gene[] geneBank) hasn't been populated with questions, or failed to load properly, its length will be 0. Trying to access any index—even 0—will throw this error immediately.
Fix: Always validate your bank has content before attempting to select a random question:
// Check if the bank is null or empty first if (geneBank == null || geneBank.Length == 0) { // Handle this case—log an error, initialize the bank, or inform the user throw new InvalidOperationException("Question bank is empty or not initialized!"); }
2. You're generating a random index that's out of bounds
Array indices start at 0 and go up to Length - 1. If you're using Random.Next() with the wrong upper bound, you'll end up with an index that doesn't exist. For example, Random.Next(geneBank.Length + 1) would generate a number up to geneBank.Length—which is one past the last valid index.
Fix: Use the array's length directly as the upper limit for Random.Next()—it's exclusive, so it will only generate valid indices from 0 to Length - 1:
var random = new Random(); int validRandomIndex = random.Next(geneBank.Length); Gene selectedQuestion = geneBank[validRandomIndex];
3. Concurrent modifications are changing the array length (if multi-threaded)
If other code is adding or removing questions from the bank while you're trying to select a random one, the length you check might not match the actual length when you access the index. For example:
- You check
geneBank.Lengthand get 5 - Another thread removes a question, making the length 4
- You try to access index 4, which no longer exists
Fix: Use a lock to ensure the array's state doesn't change between checking length and accessing the index:
// Define a lock object at the class level private readonly object _geneBankLock = new object(); // When selecting a question: lock (_geneBankLock) { int index = random.Next(geneBank.Length); Gene selected = geneBank[index]; }
4. Index calculation errors when filtering questions
If you're first filtering the bank (e.g., selecting only type == "MultipleChoice" questions), make sure the filtered subset isn't empty before trying to pick a random index. It's easy to forget that filtering might result in zero matches.
Fix: Validate the filtered collection too:
var filteredQuestions = geneBank.Where(g => g.type == "MultipleChoice").ToArray(); if (filteredQuestions.Length == 0) { throw new InvalidOperationException("No multiple choice questions found in the bank!"); } var randomIndex = random.Next(filteredQuestions.Length); var selected = filteredQuestions[randomIndex];
Quick Debug Tip
When troubleshooting, add a quick debug log to check the array length and the index you're trying to access. This will immediately tell you if the problem is an empty bank or a bad index:
Console.WriteLine($"Bank length: {geneBank.Length}, Attempted index: {randomIndex}");
内容的提问来源于stack exchange,提问作者Sondos

