Cannot implicitly convert type 'System.Collections.Generic.List<string>'
to 'System.Collections.Generic.List<Parts>'
Run Code Online (Sandbox Code Playgroud)
以下是生成此错误的代码.我很确定我做的事情很傻.
public class Parts
{
public string computername { get; set; }
public List<Parts> GetParts()
{
List<string> lst = new List<string>();
//The object that will physically connect to the database
using(SqlConnection cnx = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["request"].ConnectionString))
{
//The SQL you want to execute
SqlCommand cmd = new SqlCommand("SELECT * FROM REQUESTS", cnx);
//Open the connection to the database
cnx.Open();
//execute your command
SqlDataReader dataReader = cmd.ExecuteReader();
{
//Loop through your results
while(dataReader.Read())
{
lst.Add(Convert.ToString(dataReader["titlename"]));
}
}
}
return lst;
}
}
Run Code Online (Sandbox Code Playgroud)
该错误始终指向此行:
return lst;
Run Code Online (Sandbox Code Playgroud)
谢谢
List<string> is not the same as List<Parts>
Run Code Online (Sandbox Code Playgroud)
您正在尝试返回错误类型的列表.你的方法声明:
public List<Parts> GetParts()
Run Code Online (Sandbox Code Playgroud)
指定您返回:
List<Parts>
Run Code Online (Sandbox Code Playgroud)
但是你要回来了:
List<string>
Run Code Online (Sandbox Code Playgroud)
要更正,您应该在函数a中创建列表List<Parts>并添加Parts到列表中.或者将返回类型更改为List<string>
一个简单的错误,我自己做了几次.