首页 > 解决方案 > 存储在 C# 列表中的嵌套结构或类

问题描述

是否可以使用 c# 在列表中存储嵌套结构或类?

查看以下代码段。

嵌套结构:

struct structBooks
{
    public string strBookName;
    public string strAuthor;
    public structPubished publishedDate;
}

struct structPubished
{
    public int intDayOfMonth;
    public int intMonthOfYear;
    public int intYear;
}

保存为列表:

  static void AddBookToList()
    {
        structBooks testStruct = new structBooks();
        testStruct.strBookName = newBookName;
        testStruct.strAuthor = newAuther;
        testStruct.publishedDate.intYear = intNewYear;
        testStruct.publishedDate.intMonthOfYear = intNewMonthOfYear;
        testStruct.publishedDate.intDayOfMonth = intNewDayOfMonth;

        static List<structBooks> listBooks = new List<structBooks>();
        listBooks.Add(new structBooks()
        {
            strBookName = newBookName,
            strAuthor = newAuther,
            publishedDate.intYear = intNewYear,
            publishedDate.intMonthOfYear = intNewMonthOfYear,
            publishedDate.intDayOfMonth = intNewDayOfMonth
        });
    }

按预期创建所有 testStruct 的作品。

将结构存储为列表时,strBookName 和 strAuthor 都有效。但是,当涉及到嵌套的 publishedDate 时,Visual Studio 告诉我“无效的初始化程序成员声明器”。

其自身的列表是在 Main 方法中定义的,我刚刚添加了它,这样您就可以看到它是如何定义的。

我错过了什么?

标签: c#liststructnested

解决方案


用于new初始化您的 publishedDate struct,就像使用structBooks.

  List<structBooks> listBooks = new List<structBooks>();
  listBooks.Add(new structBooks()
  {
    strBookName = "bookName",
    strAuthor = "author",
    publishedDate = new structPubished
      {
        intDayOfMonth = 1,
        intMonthOfYear = 1,
        intYear = 1000
      }
  });

推荐阅读