c# - 存储在 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 方法中定义的,我刚刚添加了它,这样您就可以看到它是如何定义的。
我错过了什么?
解决方案
用于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
}
});
推荐阅读
- php - Laravel phpunit api返回405
- r - 使用不同的内部组件安装的自定义打包
- go - WebSocket 客户端如何知道消息已被完全读取?
- nginx - 如何使用 2 个服务器块配置 NGINX,一个通过 IP 地址访问,一个用于其他所有内容?
- google-sheets - 按名称获取图像
- javascript - 插入链表并得到 TypeError: Cannot set property 'next' of undefined
- node.js - pm2:如果在 travis-ci 中使用,则找不到命令
- php - 我想使用用户名更新订单的 WooCommerce 状态
- python - 查找一个类是否已经在python中加载?
- mysql - ER_WRONG_VALUE_COUNT_ON_ROW:列计数与第 1 行的值计数不匹配