小编kwo*_*g22的帖子

C#更改列表中的对象

我在使用找到的索引更改列表中对象的成员时遇到了一些问题.

所以这是我目前正在使用的方法:

static void addToInventory(ref List<baseItem> myArray, baseItem item, float maxAmount, ref float currentAmount)
{
    if (currentAmount + item.getWeight() <= maxAmount)
    {
        Console.WriteLine("item.Quantity = {0}", item.Quantity);
        if (myArray.Contains(item))
        {
            Console.WriteLine("Item ({0}) already exists", item.Name);
            int id = myArray.IndexOf(item);
            myArray[id].Quantity += item.Quantity;//Change occurs in this line, item.Quantity becomes the same as myArray[id].Quantity
        }
        else
        {
            Console.WriteLine("Adding new item ({0})", item.Name);
            myArray.Add(item);
        }
        currentAmount += item.getWeight();
    }
    else
    {
        Console.WriteLine("Inventory full");
    }
    myArray.Sort();
}
Run Code Online (Sandbox Code Playgroud)

此方法需要几个参数,包括清单/列表.我检查项目是否适合,如果是,我看看列表中是否有另一个相同名称的项目,找到索引,并添加更多项目.但是,添加的项目数量突然变得与列表中项目的数量相同.出于某种原因,这也会改变列表之外的项目数量.因此,而不是像这样加起来的数量:1,2,3,4,它们加起来如下:1,2,4,8.我怎样才能使添加项的数量不变?

我刚刚开始学习如何使用列表,所以如果有什么我想念,请不要犹豫批评.提前致谢.

致马克:感谢您的快速回复!对于糟糕的命名(myArray)感到抱歉; 它曾经是一个ArrayList.currentAmount和maxAmount指的是库存中的当前重量和库存可以分别持有的最大重量.另外,我不想只为数量加1; 我想要它添加我传递的项目的数量.感谢您的提示.我可能会考虑使用Dictionary.

c# list

1
推荐指数
1
解决办法
3276
查看次数

标签 统计

c# ×1

list ×1