如何正确地替换数组中的对象- c#

本文关键字:对象 数组 正确地 替换 | 更新日期: 2023-09-27 18:03:44

我试图从数组中删除一个对象,并用相同类型的对象填充槽,但所有属性都为0。但是当我这样做时,由于某种原因,当我重新计算数组值时,这些值不清除。

下面是我如何清除一个对象,并在其位置插入一个空白对象。

    public void clearOutBox(int arraySlot)
    {
        itemsInbuildArray.Remove(itemsArray[arraySlot]);
        itemsInbuildArray.Insert(arraySlot, blank);
        itemInBuildPictureArray[arraySlot].ImageLocation = null;
        statCalculation();
    }
    //one of the lines from the statCalculation method. 
    statsHealth.Text = (Convert.ToString(itemsInbuildArray.Sum(hp => hp.Health)));
        public partial class Form1 : Form
{
    List<Item> itemsArray = new List<Item>();
    List<PictureBox> itemInBuildPictureArray = new List<PictureBox>();
    List<ToolTip> itemInBuildTooltipArray = new List<ToolTip>();
    List<Item> itemsInbuildArray = new List<Item>();
            Item blank = new Item(); // this is one of several objects created here
}

我用其中的6个空白项初始化数组,用一个有值的项替换空白项没有问题,但删除它是导致我出现问题的原因。

请原谅我做这件事的方式,我刚开始学习c#,做这个项目是为了学习经验。任何输入是感激的!

如何正确地替换数组中的对象- c#

为什么不直接索引呢:

int index = 5;
array[index] = new Foobar(); // whatever your class is

这将改变数组中第6个槽中引用的内容。

我会避免使用一个名为"blank"的引用,并将其放入多个数组槽,除非你知道你永远不会修改它们。如果它们是引用类型,那么修改其中一个就会修改所有的引用类型。