【问题标题】:for not indexing correctly while foreach is workingforeach 工作时没有正确索引
【发布时间】:2023-03-22 02:00:01
【问题描述】:

我一直在使用这个类的数组并且我一直在使用 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);
    }
}

-不工作-

System.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));
    }
}

【问题讨论】:

  • 检查堆栈跟踪 - 你确定错误不是来自scorer.getScore吗?
  • 旁注:我不确定游戏是什么,但在 Yahtzee 中,5 种 可以 被视为“满屋”

标签: c# for-loop indexing


【解决方案1】:

也许问题出在其他地方。但是您可以通过查看堆栈跟踪来确定它。您也可以按如下方式更改您的 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,那么您知道它来自其他东西。

【讨论】:

  • 在别处发现的!谢谢。
猜你喜欢
  • 2019-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-21
  • 1970-01-01
  • 2014-04-24
  • 2017-11-24
  • 2023-03-17
相关资源
最近更新 更多