我有这个方法
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中包含Contact元素。
<Contacts>
<Contact>
<FirstName>Mike</FirstName>
<LastName>Phipps</LastName>
<Email>mike@contoso.com</Email>
</Contact>
<Contact>
<FirstName>Holly</FirstName>
<LastName>Holt</LastName>
<Email>holly@contoso.com</Email>
</Contact>
<Contact>
<FirstName>Liz</FirstName>
<LastName>Keyser</LastName>
</Contact>
</Contacts>
我有一个使用此代码的contact.cs
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',我应该如何更改线路才能使其正常工作?
答案 0 :(得分:8)
Contact
类的构造函数需要三个参数 - firstName
,lastName
和email
- 但是您试图在没有参数的情况下调用构造函数然后尝试使用object initializer syntax设置属性。
要修复它,您需要将三个参数传递给构造函数本身:
x => new Contact(
(string)x.Element("FirstName"),
(string)x.Element("LastName"),
(string)x.Element("Email"));
答案 1 :(得分:0)
我认为你错过了Contact中的公共构造函数。
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; }
}
或者只使用现有的构造函数。