首页 > 解决方案 > 初始化嵌套列表

问题描述

请参考以下代码

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 时,它返回错误。MAXProductDM

这是因为 CabinetList 最初是空的,并且它没有在其中显示 MIN MAX 属性。

问题

我正在使用上面的代码分配数据但返回

你调用的对象是空的。

因为 CabinetList 为空。

这里怎么初始化柜子列表???

标签: c#arrayslistinitialization

解决方案


正如Marco Forberg 的回答CabinetList所述,在构造函数中初始化

你调用的对象是空的。

例外。

除此之外,不要通过索引访问器分配Minand值: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

因为您尝试访问列表中尚不存在的项目。


推荐阅读