gpt4 book ai didi

c# - 为什么这段代码会抛出 'System.ArgumentOutOfRangeException' (SQlite)?

转载 作者:太空宇宙 更新时间:2023-11-03 18:20:28 26 4
gpt4 key购买 nike

我无法理解为什么会抛出此异常!

这是代码:

public static List<Employee> LoadEmployees()
{
List<Employee> emp = new List<Employee>();
try
{
using (SQLiteConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
cnn.Open();
string query = "select * from Employee;";
SQLiteCommand cmd = new SQLiteCommand(query, cnn);
using (var reader = cmd.ExecuteReader())
{
int i = 0;
while (reader.Read())
{
emp[i].Id = reader.GetString(0);
emp[i].Name = reader.GetString(1);
emp[i].Gender = reader.GetString(2);
emp[i].Department = reader.GetString(3);
emp[i].Doj = reader.GetString(4);
emp[i].Email = reader.GetString(5);
emp[i].Phone = reader.GetString(6);
i++;
}

}
return emp;
}

}
catch (Exception ex)
{
emp = null;
return emp;
}
}

我尝试调试并发现 -id = 'emp[i].Id' 抛出类型为 'System.ArgumentOutOfRangeException' 的异常抛出异常:mscorlib.dll 中的“System.ArgumentOutOfRangeException”

我不明白为什么它会抛出它,因为我已经初始化了 i = 0;

最佳答案

List<Employee> emp = new List<Employee>();

此时,emp,但您尝试在它仍为空时使用 emp[i] 访问项目。
如果您不想让列表再为空,您应该在某个时候使用 emp.Add(new Employee());

关于c# - 为什么这段代码会抛出 'System.ArgumentOutOfRangeException' (SQlite)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57848714/

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