在foreach工作时没有正确索引
本文关键字:索引 foreach 工作 | 更新日期: 2023-09-27 17:50:14
我已经使用这个类的数组有一段时间了,我一直在使用foreach,但是当我尝试使用for循环(实际索引)访问它时,它会离开数组。任何帮助吗?
工作——
[TestMethod]
public void Scorer_FullHouse_ReturningZero()
{
SetOfDice[] diceRolls = new SetOfDice[] {
new SetOfDice(new int[] {1,1,2,2,3}),
new SetOfDice(new int[] {3,5,3,4,3}),
new SetOfDice(new int[] {7,7,7,7,7})
};
foreach (SetOfDice roll in diceRolls)
{
int score = scorer.getScore(roll, category);
Assert.AreEqual(score, 0);
}
}
——工作——
系统。IndexOutOfRangeException:索引超出了数组的边界。
[TestMethod]
public void Scorer_ThreeOfAKind_Success()
{
SetOfDice[] diceRolls = new SetOfDice[] {
new SetOfDice(new int[] {1,2,1,4,1}),
new SetOfDice(new int[] {1,7,6,5,2}),
new SetOfDice(new int[] {8,8,8,8,8})
};
int[] expectedResults = new int[] {
9,
0,
40
};
for (int i = 0; i < expectedResults.Length; i++)
{
Assert.AreEqual(expectedResults[i], scorer.getScore(diceRolls[i], GameVariables.Category.ThreeOfAKind));
}
}
也许问题出在别的地方。但是您可以通过查看堆栈跟踪来确保这一点。你也可以这样修改for循环:
for (int i = 0; i < Math.Min(expectedResults.Length,diceRolls.length) ; i++)
{
Assert.AreEqual(expectedResults[i], scorer.getScore(diceRolls[i], GameVariables.Category.ThreeOfAKind));
}
现在,如果你用这个for循环执行它,你仍然有System.IndexOutOfRangeException
,那么你知道它来自其他地方。