我在使用找到的索引更改列表中对象的成员时遇到了一些问题.
所以这是我目前正在使用的方法:
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.
这里发生的是那个myArray[id]并item 引用同一个对象.通过引用而不是按值List.Contains进行比较.
所以看起来你想简单地做
if (myArray.Contains(item))
{
item.Quantity++;
}
Run Code Online (Sandbox Code Playgroud)
表示列表中还有一个项目.
但是,以这种方式使用列表是一种根本上不正确的方法.您应该使用Dictionary或Set来实现O(1)查找.
如果你采用字典路线,你会有类似的东西:
// a Set might be better -- I don't know what you're using this for
var myDict = new Dictionary<string, BaseItem>();
// ...
if (currentAmount + item.Weight <= maxAmount)
{
if (myDict.ContainsKey(item.Name))
{
Console.WriteLine("Item already exists");
item.Quantity++;
}
else
{
Console.WriteLine("Adding new item");
myDict[item.Name] = item;
}
currentAmount += item.Weight;
}
else
{
Console.WriteLine("Full");
}
Run Code Online (Sandbox Code Playgroud)
其他几点说明:
ref争论(除非你知道你在做什么).没有理由在这里作为参考传递不良命名myArray(myList将是一个改进,但inventory将是现场).getXXX().ref float currentAmount应该是该类的成员,而不是该方法的显式参数.