c#,lambda表达式,错误在哪里?
我有这个方法c#,lambda表达式,错误在哪里?,c#,lambda,C#,Lambda,我有这个方法 public static List<Contact> Load(string filename) { if (!File.Exists(filename)) { throw new FileNotFoundException("Data file could not be found", filename); } var contacts =
public static List<Contact> Load(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Data file could not be found", filename);
}
var contacts =
System.Xml.Linq.XDocument.Load(filename).Root.Elements("Contact").Select
(
x => new Contact() { //errors out here, XXXXXX
FirstName = (string)x.Element("FirstName"),
LastName = (string)x.Element("LastName"),
Email = (string)x.Element("Email")
}
);
return contacts.ToList();// is this line correct?, it should return List...
}
在标有“XXXXXX”的行上,我应该如何更改行以使其工作?您的
联系人
类的构造函数需要三个参数-firstName
,lastName
和email
-但是您正在尝试调用没有参数的构造函数,然后尝试使用设置属性
要修复它,您需要将三个参数传递到构造函数本身:
x => new Contact(
(string)x.Element("FirstName"),
(string)x.Element("LastName"),
(string)x.Element("Email"));
我想你失去了一个联系中的公共构造函数
public class Contact
{
public Contact() {}
public Contact(string firstName, string lastName, string email) {
FirstName = firstName;
LastName = lastName;
Email = email;
}
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public string Address { get; set; }
}
或者只使用现有的构造函数
x => new Contact(
(string)x.Element("FirstName"),
(string)x.Element("LastName"),
(string)x.Element("Email"));
public class Contact
{
public Contact() {}
public Contact(string firstName, string lastName, string email) {
FirstName = firstName;
LastName = lastName;
Email = email;
}
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public string Address { get; set; }
}