当我在一个类的属性中有一个List集合时,我的C#List不允许我向它添加数据

0 .net c# collections list

我做错了什么?

  1. 我是否需要实例化Book of Book(其他类)?

    clsP.Books = new List<Book>();
    
    Run Code Online (Sandbox Code Playgroud)
  2. 这是我在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)

Gra*_*ICA 5

错误是正确的.您需要提供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)