【发布时间】:2019-01-21 08:59:11
【问题描述】:
是否可以使用 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 方法中定义的,我只是添加了它,以便您查看它是如何定义的。
我错过了什么?
【问题讨论】:
-
你考虑过使用 DateTime 吗?
-
你可以尝试使用
{}创建和初始化publishedDate -
你不能在初始化器中使用点语法,你只能使用
new。所以你不得不说publishedDate = new structPubished { intYear = ..., intMonthOfYear = ..., intDayOfMonth = ... } -
查看Object Initializer了解详细信息。