gpt4 book ai didi

c# - 在 for 循环中迭代维度的其他部分会引发 IndexOutOfRangeException (C#)

转载 作者:太空狗 更新时间:2023-10-29 21:43:38 25 4
gpt4 key购买 nike

我在 C# 控制台应用程序中循环访问二维数组的一维时遇到问题。这是游戏的一部分,每次您投失或成功投篮时,它都会给出机智的回应。让我从我制作的二维 bool 值开始:

public static bool[,] hasResponseBeenUsedBefore = new bool[2, 11];

第一维有两行。 1 是在投篮成功时附上回应。 2 是在投篮失误时附上回应。

在我创建的用于生成响应的方法中,我尝试遍历第二个维度。

int usedManyTimes = 0;
for (int i = 0; i < hasResponseBeenUsedBefore.GetLength(1); i++)
{
MessageBox.Show(i.ToString());
if (hasResponseBeenUsedBefore[2, i] == true) // 2 is the dimension for unsuccessful responses
{
usedManyTimes++;
}
}

我试图获取第二个维度的长度,但没有成功。它抛出一个 IndexOutOfRangeException,包含以下信息:

HResult: -2146233080

Exception message: Index was outside the bounds of the array.

如有任何帮助,我们将不胜感激。感谢您的宝贵时间。

最佳答案

要获取“不成功”维度,请使用1,而不是2:

if (hasResponseBeenUsedBefore[1, i] == true)

数组使用从零开始的索引。当你定义一个数组时:

var hasResponseBeenUsedBefore = new bool[2, 11];

您使用 hasResponseBeenUsedBefore[0][0]hasResponseBeenUsedBefore[1][10] 访问它的元素。

关于c# - 在 for 循环中迭代维度的其他部分会引发 IndexOutOfRangeException (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36587449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com