gpt4 book ai didi

c# - 将 Int 值设置为数组时抛出 IndexOutOfRange 异常

转载 作者:太空宇宙 更新时间:2023-11-03 11:40:40 24 4
gpt4 key购买 nike

在我的应用程序中,一位教师可以开设多门类(class),当我排除一位教师的个人资料时,我必须先删除他的类(class)。我试图将这位老师的每个 class_id 放在一个 int 数组中,稍后删除该数组中包含该 id 的所有类(class)。

到目前为止,这是我的代码:

int x = 0;
int[] count = new int[x];

while (reader_SelectedClasses.Read())
{
if(x != 0)
{
x++;
count = new int[x];
}
count[x] = _class.Class_id = reader_SelectedClasses.GetInt16("class_id");
}

这就是

reader_SelectedClasses.Read()

做:

select class_id from tbl_class where user_id = " + id + ";

这是返回,当我在 MySQL 上尝试这个时:

enter image description here

但是当我在我的 DAO 类上运行代码时,它会返回一个 IndexOutOfRangeException。我错过了什么?已经去了here但不是很明白。有人可以用几句话解释一下并发布和固定代码吗?

最佳答案

  1. 您需要learn how to use a debugger并逐步执行您的程序。

  2. count = new int[x]; 丢弃 count 中的内容并创建一个包含零的新数组。该数组的索引从 0 到 x - 1

  3. count[x] = ... 设置索引 x 处的数组元素,根据上一行,它是数组末尾后面的一个元素。

您只需要在程序开始时设置一次count = new int[x],并且仅在以下情况下设置count[x] = ... x >= 0 且 x < count.Length。

关于c# - 将 Int 值设置为数组时抛出 IndexOutOfRange 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42055685/

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