在类中使用List <T>

Gor*_*ric 4 c# class list generic-list

我发现了一个关于在类中使用List的代码示例.有些代码我不理解.Name和Description字段在List defination中有值,但Album字段没有值.(

new genre { Name = "Rock" , Description = "Rock music", Album?? }

).为什么?

public class Genre
{
    public string  Name { get; set; }
    public string  Description { get; set; }
    public List<Album> Albums { get; set; }
}

public class Album
{
    public string  Title { get; set; }
    public decimal  Price { get; set; }
    public Genre  Genre { get; set; }
}

var genre = new List<Genre>
{
    new genre { Name = "Rock" , Description = "Rock music" },
    new genre { Name = "Classic" , Description = "Middle ages music" }
};

new List<Album>
{
    new Album { Title = "Queensrÿche", Price = 8.99M, Genre = genre.Single(g => g.Name == "Rock") },
    new Album { Title = "Chopin", Price = 8.99M, Genre = genre.Single(g => g.Name == "Classic") }
};
Run Code Online (Sandbox Code Playgroud)

Dav*_*yon 12

调用此C#语法Object and Collection initializers.

这是文档.

此语法允许您设置在初始化对象或集合期间有权访问的属性.