在book类c#控制台应用程序中使用构造函数
我有一个类,它保存了几本书并在控制台屏幕上打印出来,下面是我的代码:在book类c#控制台应用程序中使用构造函数,c#,C#,我有一个类,它保存了几本书并在控制台屏幕上打印出来,下面是我的代码: class Book { public string forfattareEfternamn; public string forfattareFornamn; public string bokensTittle; public int lanseringsDatum; public Book(string forfattareEfternamn, string forfattare
class Book
{
public string forfattareEfternamn;
public string forfattareFornamn;
public string bokensTittle;
public int lanseringsDatum;
public Book(string forfattareEfternamn, string forfattareFornamn, string bokensTittle, int lanseringsDatum)
{
}
public string BokensTittle
{
get { return bokensTittle; }
set { bokensTittle = value; }
}
public string ForfattareFornamn
{
get {return forfattareFornamn;}
set {forfattareFornamn = value;}
}
public string ForfattareEfternamn
{
get {return forfattareEfternamn;}
set {forfattareEfternamn = value;;}
}
public int LanseringsDatum
{
get { return lanseringsDatum; }
set { lanseringsDatum = value; }
}
public override string ToString()
{
return string.Format("{0}, {1}, {2}, {3} ", forfattareEfternamn, ForfattareFornamn, bokensTittle, lanseringsDatum);
}
}
主要内容:
但它给了我一个错误,说我没有接受0个参数的构造函数。有什么想法吗?如果这是您的构造函数:
public Book(string forfattareEfternamn, string forfattareFornamn, string bokensTittle, int lanseringsDatum)
{
}
(new Book { forfattareFornamn = "Dumas", forfattareEfternamn = "Alexandre", bokensTittle = "The Count Of Monte Cristo", lanseringsDatum = 1844 });
public Book() {}
这一行不会编译:
new Book { forfattareFornamn = "Dumas", forfattareEfternamn = "Alexandre", bokensTittle = "The Count Of Monte Cristo", lanseringsDatum = 1844 })
如果创建一个参数化构造函数
,则不再有默认构造函数
。因此,您遇到了此编译器错误
你可以做两件事:
1)如果您想编译它,请在您的书
类中添加一个无参数构造函数
public Book() {}
2)或更改主类中的代码,使其与参数化构造函数
新书(“废话”、“废话”等)相对应代码>首先,您的列表
初始化错误:
List<Book> books = new List<Book>(string forfatareFornamn, string forfattareEfternamn, string bokensTittle, int lanseringsDatum);
最后一个错误是调用Book
constructor的逻辑:
public Book(string forfattareEfternamn, string forfattareFornamn, string bokensTittle, int lanseringsDatum)
{
}
(new Book { forfattareFornamn = "Dumas", forfattareEfternamn = "Alexandre", bokensTittle = "The Count Of Monte Cristo", lanseringsDatum = 1844 });
public Book() {}
将其更改为:
books.Add((new Book ("Dumas", "Alexandre", "The Count Of Monte Cristo", 1844));
新书{…}
是隐式的新书(){…}
——即它使用默认构造函数。如果添加自定义构造函数,则可能还需要添加显式无参数构造函数:
public Book(string forfattareEfternamn, string forfattareFornamn, string bokensTittle, int lanseringsDatum)
{
}
(new Book { forfattareFornamn = "Dumas", forfattareEfternamn = "Alexandre", bokensTittle = "The Count Of Monte Cristo", lanseringsDatum = 1844 });
public Book() {}
这里的问题是,如果您没有定义任何构造函数(在非抽象类上),它会添加一个隐式的公共无参数构造函数,该构造函数调用:base()
——但是,如果您添加任何自定义构造函数,它会而不是这样做
或者-更改其他代码,即
books.Add(new Book("Dumas", "Alexandre", "The Count Of Monte Cristo", 1844 ));
看