无法动态设置数组初始值设定项长度

时间:2019-06-13 11:51:31

标签: c# arrays object-initializers collection-initializer

我正在使用C#挂接到FedEx API,而对于如何修改一些现有代码以满足我的需求我有些困惑。其中包含的代码段是其固定代码的一部分,在其中他们抽样如何使用一种商品。但是,当我的代码运行时,我将拥有n种商品...而且我不确定如何动态地解决这个问题。

例如,如果我有3种商品,并且手动添加3条new Commodity()语句,它将很好地工作。但是,这必须是动态的。

request.RequestedShipment.CustomsClearanceDetail.Commodities = new Commodity[3] { 
  new Commodity(), 
  new Commodity(), 
  new Commodity() 
};

这是方法的开始,第一行是我需要帮助的地方。之后,我认为根据数组大小将其他所有内容放入循环中应该没问题。

request.RequestedShipment.CustomsClearanceDetail.Commodities = new Commodity[1] { 
  new Commodity() 
};

request.RequestedShipment.CustomsClearanceDetail.Commodities[0].NumberOfPieces = "1";
request.RequestedShipment.CustomsClearanceDetail.Commodities[0].Description = "Books";
request.RequestedShipment.CustomsClearanceDetail.Commodities[0].CountryOfManufacture = "US";
//
request.RequestedShipment.CustomsClearanceDetail.Commodities[0].Weight = new Weight();
request.RequestedShipment.CustomsClearanceDetail.Commodities[0].Weight.Value = 1.0M;
request.RequestedShipment.CustomsClearanceDetail.Commodities[0].Weight.Units = WeightUnits.LB;

如果我只是这样做,就会收到错误消息:

request.RequestedShipment.CustomsClearanceDetail.Commodities = new Commodity[3] { 
  new Commodity() 
};
  

“期望长度为3的数组初始值设定项”

2 个答案:

答案 0 :(得分:4)

首先,您根本不必提及Asheet1;放=sheet2!$A$(sheet1!A1)并让系统为您计算所需的长度:

1

3

如果要创建大小为[]的数组,可以尝试使用 Linq

// Commodity[3] will be created
request.RequestedShipment.CustomsClearanceDetail.Commodities = new Commodity[] { 
  new Commodity(), 
  new Commodity(), 
  new Commodity() 
};

甚至

// Commodity[1] will be created
request.RequestedShipment.CustomsClearanceDetail.Commodities = new Commodity[] { 
  new Commodity()
};

答案 1 :(得分:0)

@Dmitry先生,几乎涵盖了以上答案中的所有内容...但是,以下部分也可以写成以下部分:

您的原始代码

request.RequestedShipment.CustomsClearanceDetail.Commodities = new Commodity[1] { 
  new Commodity() 
};

request.RequestedShipment.CustomsClearanceDetail.Commodities[0].NumberOfPieces = "1";
request.RequestedShipment.CustomsClearanceDetail.Commodities[0].Description = "Books";
request.RequestedShipment.CustomsClearanceDetail.Commodities[0].CountryOfManufacture = "US";
//
request.RequestedShipment.CustomsClearanceDetail.Commodities[0].Weight = new Weight();
request.RequestedShipment.CustomsClearanceDetail.Commodities[0].Weight.Value = 1.0M;
request.RequestedShipment.CustomsClearanceDetail.Commodities[0].Weight.Units = WeightUnits.LB;

可以进行如下修改:

修改后的动态len数组和属性初始化代码

request.RequestedShipment.CustomsClearanceDetail.Commodities = new Commodity[] { 
   new Commodity {
      NumberOfPieces = "1",
      Description = "Books",
      CountryOfManufacture = "US",
      Weight = new Weight{
            Value = 1.0M,
            Units = WeightUnits.LB
      },
      // add more properties... as per requirement
   },
   // add more objects... as per requirement
};