你能解释一下这个错误吗?

Chi*_*keh 1 c# list

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)

谢谢

Jus*_*son 10

List<string>当方法返回类型为时,您将返回a List<Part>.


Jim*_*m B 5

你的方法想要返回一个List<Parts>,但是你想要返回一个List<string>


And*_*ner 5

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>

一个简单的错误,我自己做了几次.


dkn*_*ack 5

发生错误是因为该方法应返回a List<Parts>并尝试返回aList<string>