所以我有一个程序应该采取一堆值,将它们存储在"项目"函数内部的对象,从这段代码中调用:
public IEnumerable<ProjectAll> GetAllProjects()
{
var project = pullAllProjects();
return project;
}
错误在返回项目,并显示为:
Error 1 Cannot implicitly convert type 'ProjectsApp.Models.Project'
to 'System.Collections.Generic.IEnumerable<ProjectsApp.Models.ProjectAll>'.
An explicit conversion exists (are you missing a cast?)
所以,我在StackOverflow上发现了这个: An explicit conversion exists (are you missing a cast?)
但是当我遵循这些指示时......
IEnumerable <Project> project = new Project();
while (rdr.Read())
{
project.Id = (int)rdr["project_id"];
project.Name = (string)rdr["project_name"];
project.Title = (string)rdr["project_title"];
project.Network = (int)rdr["main_network"];
project.Start = (DateTime)rdr["project_start"];
}
return project;
我在每个变量(Id,Name,ect)上都有错误。
Error 4 'System.Collections.Generic.IEnumerable<ProjectsApp.Models.Project>'
does not contain a definition for 'Name' and no extension method 'Name' accepting a
first argument of type 'System.Collections.Generic.IEnumerable<ProjectsApp.Models.Project>'
could be found (are you missing a using directive or an assembly reference?)
它似乎适用于StackOverflow链接的人,我的方式有何不同?
请提前告知我是否需要添加更多信息!
答案 0 :(得分:1)
IEnumerable<Project>
分配 Project
。正确的方法:
public IEnumrable<Project> pullAllProjects
{
.
.
.
var projects = new List<Project>();
while (rdr.Read())
{
projects.Add(new Project
{
Id = (int)rdr["project_id"];
Name = (string)rdr["project_name"];
Title = (string)rdr["project_title"];
Network = (int)rdr["main_network"];
Start = (DateTime)rdr["project_start"];
});
}
return projects;
}
答案 1 :(得分:1)
问题是在语句“IEnumerable project = new Project();”您正在尝试使用Project对象初始化IEnumerable对象。必须使用实现IEnumerable的对象初始化IEnumerable。项目不是一个可以计算的;没有办法迭代它。在这种情况下,你可以在C#,List中使用一个比较常用的IEnumerables,如下所示:
List<Project> projects = new List<Project>();
这将创建并初始化一个空的Project对象集合。
然后,将Project对象添加到List。如果您已经知道要包含在List中的对象,则可以像这样构造它:
List<Project> projects = new List<Project> { a, b, c, ... };
括号中包含的所有项目都是项目项目。
正如您应该这样做,您可以按照在代码中指定的方式添加它们:
while (rdr.Read())
{
project.Id = (int)rdr["project_id"];
project.Name = (string)rdr["project_name"];
project.Title = (string)rdr["project_title"];
project.Network = (int)rdr["main_network"];
project.Start = (DateTime)rdr["project_start"];
}