我在下面的代码中得到一个错误,它说我无法将方法组ListStudents转换为generic.list,如果我在ListStudents的末尾尝试()我得到:cant将数组转换为列表
所有即时尝试都是将一些用户硬编码到一个数组并在我的GET请求中返回它是否有解决方法?
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, UriTemplate = "")]
List<Student> GetStudentCollection();
}
[DataContract(Name="Student")]
public class Student
{
[DataMember(Name = "StudentID")]
public string StudentID { get; set; }
[DataMember(Name = "FirstName")]
public string FirstName { get; set; }
[DataMember(Name = "LastName")]
public string LastName { get; set; }
}
public class RawDataService : IReceiveData
{
public Student[] ListStudents()
{
List<Student> student = new List<Student>()
{
new Student { StudentID="bla", FirstName="bla", LastName="bla"},
new Student { StudentID="bla1", FirstName="bla1", LastName="bla1"},
new Student { StudentID="bla2", FirstName="bla2", LastName="bla2"}
};
return student.ToArray();
}
public List<Student> GetStudentCollection()
{
return ListStudents(); //error on this line, cant convert array to list
}
答案 0 :(得分:2)
ListStudents
是一种方法,而不是属性,所以试试这个:
return ListStudents();
另外,更改ListStudents()
方法以返回List
,如下所示:
public List<Student> ListStudents()
{
List<Student> student = new List<Student>()
{
new Student { StudentID="bla", FirstName="bla", LastName="bla"},
new Student { StudentID="bla1", FirstName="bla1", LastName="bla1"},
new Student { StudentID="bla2", FirstName="bla2", LastName="bla2"}
};
return student;
}
答案 1 :(得分:1)
尝试使用ToList
linq扩展方法:
using System.Linq;
...
public Student[] ListStudents()
{
List<Student> student = new List<Student>()
{
new Student { StudentID="bla", FirstName="bla", LastName="bla"},
new Student { StudentID="bla1", FirstName="bla1", LastName="bla1"},
new Student { StudentID="bla2", FirstName="bla2", LastName="bla2"}
};
return student.ToArray();
}
public List<Student> GetStudentCollection()
{
return ListStudents().ToList(); //<-- this is the change you need
}
但是,要减少转化次数,我建议您更改方法如下:
public Student[] ListStudents()
{
return GetStudentCollection().ToArray();
}
public IList<Student> GetStudentCollection()
{
var students = new List<Student>()
{
new Student { StudentID="bla", FirstName="bla", LastName="bla"},
new Student { StudentID="bla1", FirstName="bla1", LastName="bla1"},
new Student { StudentID="bla2", FirstName="bla2", LastName="bla2"}
};
return students();
}
答案 2 :(得分:1)
除非您有使用数组的原因,否则只返回列表。为什么要花费CPU转换为数组,然后备份到List:
public class RawDataService : IReceiveData
{
public List<Student> ListStudents()
{
List<Student> students = new List<Student>()
{
new Student { StudentID="bla", FirstName="bla", LastName="bla"},
new Student { StudentID="bla1", FirstName="bla1", LastName="bla1"},
new Student { StudentID="bla2", FirstName="bla2", LastName="bla2"}
};
return students;
}
public List<Student> GetStudentCollection()
{
return ListStudents(); //error on this line, cant convert array to list
}
但是,如果必须返回数组,则将错误的行更改为:
using System.Linq;
...
return ListStudents().ToList();