【问题标题】:List<T> using inside a class在类中使用 List<T>
【发布时间】:2013-03-27 13:42:31
【问题描述】:

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

【问题讨论】:

  • 哪一部分你不明白? NameDescription 值已设置,而 Albums 未设置。它与genre.Name = "Rock"; genre.Description = "Rock Music"; 相同,而不是genre.Albums = whatever

标签: c# list class generic-list


【解决方案1】:

此 C# 语法称为 Object and Collection initializers

这里是documentation

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

【讨论】:

    【解决方案2】:

    这些是Object and Collection Initializers,用于快速初始化属性。您无需初始化所有属性,只需初始化您需要的属性即可。

    【讨论】:

      【解决方案3】:

      因为编码器不想设置它的值。如果要在末尾添加语句 Album = new List()。您不需要设置所有属性。

      【讨论】:

        【解决方案4】:

        正如其他人所提到的,代码示例使用Object and Collection Initializers。对于集合,初始化程序调用集合的构造函数,然后为花括号内列出的每个元素调用 .Add() 函数。对于对象,初始化程序调用对象的构造函数,然后为您指定的任何属性设置值。

        对象和集合初始化器实际上在临时变量中创建您的对象或集合,然后将结果分配给您的变量。这可确保您获得全有或全无的结果(即,如果您在初始化期间从另一个线程访问它时无法获得部分初始化的值)。初始化代码可以改写如下:

        var temp_list = new List<Genre>();
        // new genre { Name = "Rock" , Description = "Rock music" }
        var temp_genre_1 = new Genre();
        temp_genre_1.Name = "Rock";
        temp_genre_1.Description = "Rock music";
        temp_list.Add(temp_genre_1);
        // new genre { Name = "Classic" , Description = "Middle ages music" }
        var temp_genre_2 = new Genre();
        temp_genre_2.Name = "Classic";
        temp_genre_2.Description = "Middle ages music";
        temp_list.Add(temp_genre_2);
        // set genre to the result of your Collection Initializer
        var genre = temp_list;
        

        由于此代码没有显式设置流派的 Album 属性的值,因此它被设置为您的 Genre 类中指定的默认值(对于引用类型为 null)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-02-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多