是否可以使用 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/