c# - 存储在 c# 列表中的嵌套结构或类

标签 c# list struct nested

是否可以使用 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 方法中定义的,我只是添加它以便您可以看到它是如何定义的。

我错过了什么?

最佳答案

使用 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
      }
  });

关于c# - 存储在 c# 列表中的嵌套结构或类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54286365/

相关文章:

java - 字符不会存储在列表中

c - C 中的结构体初始化

c - 结构标签和花括号后面的标签有什么区别?

C# - ObjectContext 实例已被释放,不能再用于需要连接的操作

c# - 补码转换

C++ Builder 2009 - 简单的整数列表

c - 如何以非标准方式在 C 中键入定义结构

c# - c# 与 vb.net 中的 lambda 表达式

c# - 16 位数字的基本正则表达式

对象列表中的 Python 返回具有类属性集的第一个对象