gpt4 book ai didi

c# - List 在类中使用

转载 作者:太空狗 更新时间:2023-10-29 23:59:01 27 4
gpt4 key购买 nike

我找到了一个关于在类中使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com