【发布时间】:2014-12-02 22:17:37
【问题描述】:
我正在尝试创建一个用于存储灯具列表的列表方法。目前我的代码的if (fixtures[i] != lineup) 部分不断出现错误,我无法弄清楚为什么。我不断收到以下错误。
在 mscorlib.dll 中发生了“System.ArgumentOutOfRangeException”类型的未处理异常
附加信息:索引超出范围。必须是非负数且小于集合的大小。
我不明白为什么这是个问题,因为如果 fixtures[i] 肯定是 null 那么它应该添加阵容吗?
private List<string> GenerateFixtures()
{
List<string> fixtures = new List<string>(); // Create a new list to store the games
while (fixtures.Count < 7) // There can only be 6 possible games
{
Random random = new Random(DateTime.UtcNow.Millisecond); // Generate a new random
int home = random.Next(0, 3); // Home team number
int away = random.Next(0, 3); // Away team number
if (home == away) // If they are the same teams
{
while (home == away) // whilst they are equal to eachother
{
away = random.Next(0, 3); // generate new away team
}
}
string lineup = string.Format("{0} v {1}", home, away); // convert it to a string
for (int i = 0; i <= fixtures.Count; i++) // whilst i is 0
{
if (fixtures[i] != lineup) // if fixtures is not equal to lineup
fixtures.Add(lineup); // add it
}
} // loop through till it is done
return fixtures; // then return it
}
我也有点担心,我会以错误的方式创建它。我有 4 个团队 - 团队 0、1、2、3,他们应该随机互相比赛(我使用随机,所以它总是一个不同的阵容,因为我计划将它用于其他组)。
0 对 1 || 2 对 3 || 2 对 1 || 3 对 0 || 1 对 3 || 0 v 2
有没有更好的方法来做到这一点?
我还刚刚注意到,我这样做的方式将允许将 0 v 1 和 1 v 0 添加到列表中,因为它们是不同的。
【问题讨论】:
-
你想做什么?创建一个没有重叠的对列表?使用像鸽笼这样的简单算法而不是随机数会好得多。
-
将 Random 的创建移到循环之外。您可能会得到重复项,并且只需要创建一次。