我做错了什么?
我是否需要实例化Book of Book(其他类)?
clsP.Books = new List<Book>();
Run Code Online (Sandbox Code Playgroud)这是我在linqpad中得到错误的行
'UserQuery.Book'不包含带3个参数的构造函数
var book1 = new Book("Neuromancer", "William Gibson", "Science Fiction");
Run Code Online (Sandbox Code Playgroud)这是完整的代码,有什么问题?
void Main()
{
var clsPList = new List<clsPerson>();
var clsP = new clsPerson();
clsP.FirstName = "jack";
clsP.LastName = "barker";
clsP.Gender = "male";
//clsP.Books = new List<Book>();
var book1 = new Book("Neuromancer", "William Gibson", "Science Fiction");
clsP.Books.Add(book1);
clsPList.Add(clsP);
clsPList.Dump();
}
public class clsPerson
{
public string FirstName;
public string LastName;
public string Gender;
public List<Book> Books = new List<Book>();
}
public class Book
{
public string Title;
public string Author;
public string Genre;
}
Run Code Online (Sandbox Code Playgroud)
错误是正确的.您需要提供Book有效的构造函数...
public class Book
{
public Book(string title, string author, string genre)
{
Title = title;
Author = author;
Genre = genre;
}
public string Title;
public string Author;
public string Genre;
}
Run Code Online (Sandbox Code Playgroud)
...或者直接分配给属性:
var book1 = new Book {
Title = "Neuromancer",
Author = "William Gibson",
Genre = "Science Fiction"
};
Run Code Online (Sandbox Code Playgroud)