我想使用C#中的存储过程和datareader返回记录列表。当前,它给了我错误
无法将类型“ ClsHorseTracker”隐式转换为“ System.Collections.Generic.List”
代码:
public List<ClsHorseTracker> HorseTrackerList()
{
clsUtilities clsUtilities = new clsUtilities();
DataSet ds;
List<ClsHorseTracker> clsHorseTracker = new List<ClsHorseTracker>();
string sSQL = "exec HorseDetails";
ds = clsUtilities.GetDataSet(sSQL);
SqlCommand cmd = new SqlCommand();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
clsHorseTracker = new ClsHorseTracker
{
HorseName = Convert.ToString(reader["HorseName"]),
HorseTypeName = Convert.ToString(reader["HorseTypeName"]),
};
}
}
}
return clsHorseTracker;
}
答案 0 :(得分:1)
clsHorseTracker是ClsHorseTracker的列表。因此,您需要在“ while”循环中将新对象添加到列表中,而不是将对象分配到列表中 试试这个
public List<ClsHorseTracker> HorseTrackerList()
{
clsUtilities clsUtilities = new clsUtilities();
DataSet ds;
List<ClsHorseTracker> clsHorseTracker = new List<ClsHorseTracker>();
string sSQL;
sSQL = "exec HorseDetails";
ds = clsUtilities.GetDataSet(sSQL);
SqlCommand cmd = new SqlCommand();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
clsHorseTracker.Add(new ClsHorseTracker
{
HorseName = Convert.ToString(reader["HorseName"]),
HorseTypeName = Convert.ToString(reader["HorseTypeName"]),
});
}
}
}
return clsHorseTracker;
}