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 =
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...
}
我Contacts.xml与它联系的元素。
<Contacts>
<Contact>
<FirstName>Mike</FirstName>
<LastName>Phipps</LastName>
<Email>[email protected]</Email>
</Contact>
<Contact>
<FirstName>Holly</FirstName>
<LastName>Holt</LastName>
<Email>[email protected]</Email>
</Contact>
<Contact>
<FirstName>Liz</FirstName>
<LastName>Keyser</LastName>
</Contact>
</Contacts>
我有这个代码
public class 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; }
}
就行了,在那里与“XXXXXX”打上了contact.cs,我应该怎么改线,使其工作?
答
您Contact
类的构造函数需要三个参数 - firstName
,lastName
和email
- 但你试图调用不带参数的构造函数,然后试图设置使用object initializer syntax属性。
要解决它,你需要将三个参数传递到构造函数本身:
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; }
}
或者只是使用现有的构造函数。
谢谢,代码现在编译。 – user149169 2009-08-09 21:55:06