初始化新对象的问题

时间:2015-10-08 19:17:24

标签: c# object constructor

当我尝试构造以下对象时:

Tijdschrift tijdschrift = new Tijdschrift 
{ 
    Id = "ID01", 
    Titel = "Scientific American", 
    Datum = new DateTime(2014, 8, 1), 
    Uitgeverij = "Scientific American" 
};

我收到以下错误:

  

错误CS7036没有给出对应于所需形式参数的参数' Id' of' Tijdschrift.Tijdschrift(string,string,DateTime,string)'目录C:\ Users \ Robiin \ Documents \ Labo03 \ Labo03 \ Program.cs 13

我不知道为什么说实话,我的构造函数如下所示。

public Tijdschrift(string Id, string titel, DateTime datum, string uitgeverij)
{
    Datum = datum;
    this.Id = Id;
    Titel = titel;
    Uitgeverij = uitgeverij;
}

3 个答案:

答案 0 :(得分:2)

您正在使用object initializer语法。您首先发布的代码尝试调用无参数构造函数,然后设置属性。使用括号()传递构造函数参数:

Tijdschrift tijdschrift = new Tijdschrift ("ID01", 
    "Scientific American", 
    new DateTime(2014, 8, 1), 
    "Scientific American");

答案 1 :(得分:0)

尝试调用这样的构造函数:

Tijdschrift tijdschrift = new Tijdschrift ("ID01",
                                           "Scientific American",
                                            new DateTime(2014, 8, 1),
                                            "Scientific American");

答案 2 :(得分:0)

您问题的另一个解决方案是添加无参数构造函数。然后你的对象初始化程序工作正常。

public class Tijdschrift {
    public DateTime Datum {get;set;}
    public string Id {get;set;}
    public string Titel {get;set;}
    public string Uitgeverij {get;set;}

    public Tijdschrift(){}

    public Tijdschrift(string Id, string titel, DateTime datum, string uitgeverij)
    {
        Datum = datum;
        this.Id = Id;
        Titel = titel;
        Uitgeverij = uitgeverij;
    }
}
相关问题