Foreach through rows in DataTable: 'Cannot apply indexing with [] to an expression of type 'object' ' 获取单元格值时

Foreach through rows in DataTable: 'Cannot apply indexing with [] to an expression of type 'object' ' when getting cell value

我收到以下错误:'无法将 [] 的索引应用于 'object' 类型的表达式 '

private void InitAllTimeSlots()
{
    var table = new DataTable();
    string query = $"select TimeSlot from Time_Slot";
    _allTimeSlots = new List<string>();
    using (var connection = new System.Data.SqlClient.SqlConnection(
          @"Data Source=********;Initial Catalog=*****;User ID=****;Password=******"))
    {
        using (var adapter = new System.Data.SqlClient.SqlDataAdapter(query, connection))
        {
            // adapter.SelectCommand = command
            // adapter.SelectCommand.CommandText = query
            adapter.Fill(table);
            foreach (var obj in table.Rows)
                _allTimeSlots.Add(obj[0]);   //ERROR HERE
        }
    }
}

只需将您的 foreach 更改为:

foreach (DataRow obj in table.Rows)
    _allTimeSlots.Add(obj[0].ToString());