c# - 初始化嵌套列表
问题描述
请参考以下代码
List<ProductDM> productDMList = _orderRepo.GetProductList(32, 12);
for (int i=0;i<productDMList.Count;i++)
{
productDMList[i].CabinetList[i].Min = productDMList[i].Min;
productDMList[i].CabinetList[i].Max = productDMList[i].Max;
}
public class ProductDM
{
public List<InventoryDM> CabinetList { get; set; }
public double Min { get; set; }
public double Max { get; set; }
}
public class InventoryDM
{
public Double Min { get; set; }
public Double Max { get; set; }
}
要求是循环productDMList
并绑定内阁列表中的返回值MIN
和值。填充 MIN 和 MAX 金额,但将它们分配给 CabinetList 时,它返回错误。MAX
ProductDM
这是因为 CabinetList 最初是空的,并且它没有在其中显示 MIN MAX 属性。
我正在使用上面的代码分配数据但返回
你调用的对象是空的。
因为 CabinetList 为空。
这里怎么初始化柜子列表???
解决方案
正如Marco Forberg 的回答CabinetList
所述,在构造函数中初始化
你调用的对象是空的。
例外。
除此之外,不要通过索引访问器分配Min
and值:Max
productDMList[i].CabinetList[i].Min = productDMList[i].Min;
productDMList[i].CabinetList[i].Max = productDMList[i].Max;
您应该使用以下类型的Add()
方法List<>
:
productDMList[i].CabinetList.Add(new InventoryDM { Min = productDMList[i].Min, Max = productDMList[i].Max });
否则你会得到一个
参数OutOfRangeException
因为您尝试访问列表中尚不存在的项目。
推荐阅读
- css - 将具有溢出内容的弹性项目拉伸到其容器的完整可用宽度
- vis.js - vis.js 如何以最短连接线长度的布局显示网络?
- sql - 并行查询执行正在减慢 Postgresql
- c# - EF BulkInsert 未在 Task.Run() 中触发
- r - Automatic matching of right column
- apollo-client - com.apollographql.apollo.exception.ApolloParseException:无法解析 http 响应
- postgresql - 功能没有响应预期的结果?
- python - 使用 python 脚本将数据写入 unix 中的文件的问题
- php - Laravel 从 5.8 到 6 更新项目的问题
- reactjs - 对内容繁重的页面做出反应预加载建议