C# 如何使用中的列表初始化类?
基本问题但我在任何地方都找不到,我有两门课:C# 如何使用中的列表初始化类?,c#,list,C#,List,基本问题但我在任何地方都找不到,我有两门课: 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 I
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; }
}
公共课堂教材
{
公共int Id{get;set;}
公共字符串类别{get;set;}
公共字符串标题{get;set;}
公共IList章{get;set;}
}
公共课章节
{
公共int Id{get;set;}
公共字符串标题{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" }
});
var books=newlist();
books.Add(新书)
{
Id=1,
Category=“test”,
Title=“Book1测试”,
章=新章(){Id=1,Title=“A”},
新章节(){Id=2,Title=“B”}
});
但我得到了一个错误:无效的初始值设定项成员声明符?我想您需要
Chapters = new List<Chapter>()
{
new Chapter() { Id = 1, Title = "A"},
new Chapter() { Id = 2, Title = "B" }
}
书籍
类没有名为答案
newchapter(){…}
)放在集合初始值设定项中Chapters = new List<Chapter>()
{
new Chapter() { Id = 1, Title = "A"},
new Chapter() { Id = 2, Title = "B" }
}
书籍
类没有名为答案
newchapter(){…}
)放在集合初始值设定项中塞尔曼22有一个答案。另一种可能是在实例化对象时初始化列表:
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>();
}
}
公共课堂教材
{
公共int Id{get;set;}
公共字符串类别{get;set;}
公共字符串标题{get;set;}
公共IList章{get;set;}
公共书籍()
{
章节=新列表();
}
}
它不再是一个IList,它只是一个列表。然而,人们总是可以忽略它。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>();
}
}
公共课堂教材
{
公共int Id{get;set;}
公共字符串类别{get;set;}
公共字符串标题{get;set;}
公共IList章{get;set;}
公共书籍()
{
章节=新列表();
}
}
它不再是一个IList,它只是一个列表。尽管如此,人们还是可以覆盖它。如果你给
书
一个初始化章节的构造函数
:
public Book
{
public Book()
{
Chapters = new List<Chapter>();
}
// properties
}
请注意,如果您没有在构造函数中初始化
章节
,这仍然是合法的,但是它会在运行时抛出NullReferenceException
。如果您给Book
一个初始化章节
的构造函数:
public Book
{
public Book()
{
Chapters = new List<Chapter>();
}
// properties
}
请注意,如果您没有在构造函数中初始化
章节
,这仍然是合法的,但是它会在运行时抛出NullReferenceException
。答案应该是章节吗?是的,将编辑章节初始化。答案应该是章节吗?是的,将编辑章节初始化。sry,是的,请参见上文,应为章节-例如,书籍应包含与其相关的章节。sry,是的,请参见上文,应为章节-例如,书籍应包含与其相关的章节。我认为您只能在初始化之后立即使用该初始值设定项语法:Chapters=new List(){new Chapter(),…}
@theevillpenguin您也可以使用它,如我所示。我确实在LINQPad中尝试过它,但它不起作用,但现在我包含了完整的示例,它确实起作用了。我想我需要学习一些东西。我想你只能在初始化之后使用初始化器语法:Chapters=new List(){new Chapter()…,…}
@theevillpenguin你也可以使用它,正如我所展示的那样。我确实在LINQPad中尝试过它,但它不起作用,但现在我包含了完整的示例,它确实起作用了。我想我还有一些学习要做。