基本问题,但我无法在任何地方找到anwser,我有2个课程:
public class Book
{
public int Id { get; set; }
public string Category { get; set; }
public string Title { get; set; }
public IList<Chapter> Chapters{ get; set; }
}
public class Chapter
{
public int Id { get; set; }
public string Title { get; set; }
}
如何添加或初始化?我试过了:
var books = new List<Book>();
books.Add(new Book()
{
Id = 1,
Category = "test",
Title = "Book1 test",
Chapters = new Chapter() { Id = 1, Title = "A"},
new Chapter() { Id = 2, Title = "B" }
});
但是我收到错误:初始化程序成员声明符无效?
答案 0 :(得分:5)
我想你想要
Chapters = new List<Chapter>()
{
new Chapter() { Id = 1, Title = "A"},
new Chapter() { Id = 2, Title = "B" }
}
而不是:
Answers = new Chapter() { Id = 1, Title = "A"},
new Chapter() { Id = 2, Title = "B" }
Book
班级没有名为Answers
new Chapter() { ... }
)放在集合初始化程序中。答案 1 :(得分:1)
如果您为Book
提供初始化Chapters
的构造函数:
public Book
{
public Book()
{
Chapters = new List<Chapter>();
}
// properties
}
您将能够使用集合初始化程序语法:
var book = new Book()
{
Id = 1,
Category = "test",
Title = "Book1 test",
Chapters = { new Chapter() { Id = 1, Title = "A" },
new Chapter() { Id = 2, Title = "B" } }
};
请注意,如果您未在构造函数中初始化Chapters
,这仍然是合法的,但它会在运行时抛出NullReferenceException
。
答案 2 :(得分:0)
Selman22有一个答案。另一个可能是在对象的实例化时初始化列表:
public class Book
{
public int Id { get; set; }
public string Category { get; set; }
public string Title { get; set; }
public IList<Chapter> Chapters{ get; set; }
public Book()
{
Chapters = new List<Chapter>();
}
}
它不再是IList,它只是一个List。人们总是可以覆盖它。