Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c#,lambda表达式,错误在哪里?_C#_Lambda - Fatal编程技术网

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; }
}