将元素添加到数组

时间:2010-04-02 18:51:46

标签: c#

好的,我无法得到这个。我看了它,我不明白为什么它超出界限。我在paypalItems[paypalItems.Length] = new PaymentDetailsItemType

收到错误
PaymentDetailsItemType[] paypalItems = new PaymentDetailsItemType[order.OrderItems.Count];

for (int i = 0; i < order.OrderItems.Count; i++)
{

    paypalItems[i] = new PaymentDetailsItemType
    {
        Name = order.OrderItems[i].Name,
        Amount = ApiUtility.CreateBasicAmount(order.OrderItems[i].Price),
        Description = order.OrderItems[i].Name,
        Number = order.OrderItems[i].Sku,
    };
}

// paymentItems now has 1 item...now to the if statement:

if (giftCardsTotal != 0)
{
    // add Coupons & Discounts line item
    paypalItems[paypalItems.Length] = new PaymentDetailsItemType
                                              {
                                                  Name = "Gift Cards",
                                                  Amount = ApiUtility.CreateBasicAmount(giftCardsTotal),
                                                  Description = "Gift Cards"
                                              };
}

更新:我改变了数组的大小..现在一切都很好。不需要-1

PaymentDetailsItemType[] paypalItems = new PaymentDetailsItemType[order.OrderItems.Count + 1];

            for (int i = 0; i < order.OrderItems.Count; i++)
            {
                paypalItems[i] = new PaymentDetailsItemType
                {
                    Name = order.OrderItems[i].Name,
                    Amount = ApiUtility.CreateBasicAmount(order.OrderItems[i].Price),
                    Description = order.OrderItems[i].Name,
                    Number = order.OrderItems[i].Sku,
                };
            }

        // paymentItems now has 1 item...now to the if statement:

            if (giftCardsTotal != 0)
            {
                paypalItems[paypalItems.Length -1] = new PaymentDetailsItemType
                {
                    Name = "Certificates",
                    Amount = ApiUtility.CreateBasicAmount(giftCardsTotal),
                    Description = "Certificates"
                };
            }

11 个答案:

答案 0 :(得分:11)

我认为你最好使用List<>,所以你会声明:

List<PaymentDetailsItemType> paypalItems = new List<PaymentDetailsItemType>();

然后当你遍历order.OrderItems时,只需要做一个paypalItems.Add()

最后在if(giftCardsTotal != 0)有条件的情况下,只需执行以下操作:

paypalItems.Add(new PaymentDetailsItemType...);

通过这种方式,您不必担心关闭一个数组索引问题。这将是重写的代码(为方便起见,我使用var):

var paypalItems = new List<PaymentDetailsItemType>();

foreach (var orderitem in order.OrderItems)
{
    paypalItems.Add(new PaymentDetailsItemType
    {
        Name = orderitem.Name,
        Amount = ApiUtility.CreateBasicAmount(orderitem.Price),
        Description = orderitem.Name,
        Number = orderitem.Sku,
    });
}

if (giftCardsTotal != 0)
{
    // add Coupons & Discounts line item
    paypalItems.Add(new PaymentDetailsItemType
    {
        Name = "Gift Cards",
        Amount = ApiUtility.CreateBasicAmount(giftCardsTotal),
        Description = "Gift Cards"
    });
}

John Saunders '建议(在评论中),这是Linq对变量声明和第一个循环的替代:

var paypalItems = 
    (from orderitem in order.OrderItems
    select new PaymentDetailsItemType
    {
        Name = orderitem.Name,
        Amount = ApiUtility.CreateBasicAmount(orderitem.Price),
        Description = orderitem.Name,
        Number = orderitem.Sku
    }).ToList();

根据评论添加:如果您在完成后需要Array,请致电:

paypalItems.ToArray()

答案 1 :(得分:9)

数组在C#中基于零。使用array[array.Length]将始终失败。你想要Length-1


此外,我发现你正在尝试扩展阵列。你做不到!一旦数组被实例化,它的长度就不会改变。

如果您需要可以展开的集合,请使用List<PaymentDetailsItemType>

答案 2 :(得分:2)

因为它们是0索引的,所以第一个是0,最后一个是length-1

对于几乎所有编程语言都是如此..

似乎首先通过转换另一个数组中的元素来填充数组,然后你想要替换最后一个。也许你打算在最后添加一个元素?

在这种情况下,您应该将其构建得更大:

PaymentDetailsItemType[] paypalItems = new PaymentDetailsItemType[order.OrderItems.Count+1];

然后像你一样填写它:

for (int i = 0; i < order.OrderItems.Count; i++)
{
  ...
}

然后设置最后一个:

paypalItems[paypalItems.Length-1] = ..

答案 3 :(得分:1)

paypalItems[paypalItems.Length] = 

应该是

paypalItems[paypalItems.Length - 1] = 

答案 4 :(得分:1)

此:

paypalItems[paypalItems.Length]

当数组索引从0开始时,将始终位于数组的边界之外。如果要在数组的最后一个元素中存储某些内容,请执行以下操作:

paypalItems[paypalItems.Length-1] = ...

答案 5 :(得分:1)

看起来你正试图通过简单地使用下一个索引来附加到数组。也许你是通过接触像javascript或python这样的语言学到的,其中“数组”实际上是复杂的对象。真正的数组不能那样工作。

相反,您应该尝试使用.Add()的{​​{1}}方法。

答案 6 :(得分:1)

在添加新数组项之前,您需要更改数组的大小。

if(giftCardsTotal!= 0)

{

// Increase the size
Array.Resize(ref paypalItems, paypalItems.Length + 1);

// add Coupons & Discounts line item
paypalItems[paypalItems.Length -1] = new PaymentDetailsItemType
                                          {
                                              Name = "Gift Cards",
                                              Amount = ApiUtility.CreateBasicAmount(giftCardsTotal),
                                              Description = "Gift Cards"
                                          };

}

答案 7 :(得分:0)

长度从1开始,索引从0开始。所以你应该尝试:

paypalItems[paypalItems.Length - 1]

答案 8 :(得分:0)

paypalItems[paypalItems.Length]将访问分配空间上方的一个位置。如果您想要最后一个位置,则需要paypalItems[paypalItems.Length-1]

如果要附加项目,请使用列表&lt;&gt;而不是数组。

答案 9 :(得分:0)

您正在将数组初始化为order.OrderItems.Count的长度,然后在填充数据后,您尝试向阵列添加其他项。这不会像这样工作。您已在此处为数组分配了静态大小,如果没有某种重新分配,则无法向其中添加其他项目。

您需要创建动态分配的数组或使用List<T>

答案 10 :(得分:0)

要添加到其他答案,.NET中的Array是一种低级数据类型,它直接映射到内存中已分配的字节序列。因此,如果数组已经已满,则无法将其添加到数组中。也许您正在寻找的是使用List<T>

var paypalItems = new List<PaymentDetailsItemType>(order.OrderItems.Count);
// specifying that count is optional, but will increase performance because array space will have to be reallocated less often

// ...
paypalItems.Add(new PaymentDetailsItemType
                                              {
                                                  Name = "Gift Cards",
                                                  Amount = ApiUtility.CreateBasicAmount(giftCardsTotal),
                                                  Description = "Gift Cards"
                                              });
相关问题