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

la2*_*a27 1 c# sqlite exception

我无法理解为什么会引发此异常!

这是代码:

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;
            }
        }
Run Code Online (Sandbox Code Playgroud)

我尝试调试,发现-id ='emp [i] .Id'引发了类型'System.ArgumentOutOfRangeException'的异常'mscorlib.dll中引发了异常:'System.ArgumentOutOfRangeException'

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

Raf*_*lon 6

List<Employee> emp = new List<Employee>();
Run Code Online (Sandbox Code Playgroud)

此时,emp,但您尝试通过emp[i]在其仍为空时使用来访问项目。如果您不希望列表为空,
则应emp.Add(new Employee());在某个时候使用。