gpt4 book ai didi

C# 更改列表中的对象

转载 作者:太空宇宙 更新时间:2023-11-03 17:22:48 25 4
gpt4 key购买 nike

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

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

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();
}

此方法采用多个参数,包括库存/列表。我检查该项目是否适合,如果适合,我会查看列表中是否有另一个同名项目,找到索引,然后添加更多项目。但是,添加的项目数量突然变得与列表中项目的数量相同。出于某种原因,这也会更改列表外项目的数量。因此,不是像这样加起来的数量:1、2、3、4,而是像这样加起来:1、2、4、8。我怎样才能使添加的项目的数量不变?

我刚刚开始学习如何使用列表,所以如果有任何遗漏,请不要犹豫批评。提前致谢。

致马克:感谢您的快速回复!抱歉命名不当(myArray);它曾经是一个 ArrayList。 currentAmount和maxAmount分别是指库存中的当前重量和库存的最大重量。另外,我不想只在数量上加 1;我希望它添加我传递的项目的数量。感谢您的提示。我可能会考虑改用字典。

最佳答案

这里发生的事情是 myArray[id]item 指的是同一个对象List.Contains 按引用 进行比较,而不是按值进行比较。

所以它看起来就像您想简单地做

if (myArray.Contains(item))
{
item.Quantity++;
}

表示列表中还有一项。

但是,以这种方式使用列表是一种根本上不正确的方法。您应该使用字典或集合来实现 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");
}

一些其他注意事项:

  • 避免ref arguments (除非你知道你在做什么)。没有理由将命名不当的 myArray(myList 会有所改进,但 inventory 会很准确)在这里作为引用传递.
  • 首选 properties通过 getXXX() 方法。
  • 优先使用类而不是任意静态方法。您在此处描述的方法听起来像是属于 Inventory 类,而不是某种与某处特定实例无关的静态方法。 ref float currentAmount 应该是类的成员,而不是方法的显式参数。
  • 运行 StyleCop在你的代码上。 Make it a pre-build event .这将迫使您养成良好的 C# 风格习惯,例如使用大写字母命名类和方法(以及在 get/set 方法上使用属性)。

关于C# 更改列表中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2962803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com