c# - List<T> 在类中使用

标签 c# list class generic-list

我找到了一个关于在类中使用 List 的代码示例。有些代码我不明白。Name 和 Description 字段在 List 定义中有值,但 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") }
};

最佳答案

此 C# 语法称为对象和集合初始值设定项

这是 documentation .

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

关于c# - List<T> 在类中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15660345/

相关文章:

android - 在 Android NDK 中使用一个简单的 C++ 类

c# - 唯一的持久性控件标识符

c# - 如何在 Xamarin.Forms 上使用 System.Data.SQLite Interop.dll?

c# - 与 C# 中的泛型类型有些混淆

c# - Linq 不在数据表上的选择中

c# - 对象列表,获取带有分隔符的属性

python - 如何制作新的数字列表而不 append 到自己的列表中?

arrays - 嵌套列表最后一行元素重复所有前面的行

c++ - 在另一个模板类中使用模板类类型的变量

c++ - 如何存储对象供以后使用并使它们可搜索