繁体   English   中英

如何将变量的值存储在列表中,并且在更改变量时不更改它的值?

[英]How to store a variable's value in a list and not have it changed when that variable is altered?

我正在尝试一个列表,其中存储了字符在其中的当前位置以及以前的位置。 在此代码开始之前,字符将移动一列/行,并用另一种方法更新它的current_position。 如果位置列表大于(move_counter + 1),则将删除第一项。

但是,当我运行这部分代码时,先前存储在列表中的current_position也将更改。

假设我们从一个列表开始:{[6,7],[7,7]}和当前位置[7,7]。 (这些是我输入的默认初始值,[6,7]是随机起始位置,[7,7]是初始current_position)

移至位置[8,7]后,列表立即更改为{[6,7],[8,7]}。 然后,在运行代码时,它将变为{[8,7],[8,7]},而应将其变为{[7,7],[8,7]},存储最后一个已知的current_position和当前当前位置。

 list_size= known_cells.Count; known_cells.Add(current_position); if (list_size > (move_counter + 1)) { dataGridView1.Rows[known_cells[0][0]].Cells[known_cells[0][1]].Style.BackColor = Color.LightGray; known_cells.RemoveAt(0); } 

希望这不是一个混乱的解释。 先谢谢您的帮助。

该列表为{[8,7],[8,7]},因为在此代码之前,您已将当前位置更新为[8,7]。 要分解,

列表变为{[6,7],[8,7]}。

然后,known_cells.Add(current_position); 将添加当前位置[8,7]。 因此,列表变为{[6,7],[8,7],[8,7]}。

现在,“ if”条件将删除第一个元素[6,7]。

因此,您将剩下列表{[8,7],[8,7]}

我建议您添加[8,7]而不是将[7,7]替换为[8,7],然后删除第一个元素。 希望这不是一个混乱的解释:)

我怀疑您的current_position是某种引用类型。 然后,当您执行known_cells.Add(current_position) ,您不是在添加当前 ,而是对该值的引用

当您以后更改属性时,通过列表中的引用也可以看到这些更改。

解决方案:更改为“不可变”类。 所以代替

class ThePosition
{
   public int Coord1 {get; set;}
   public int Coord2 {get; set;}

   public ThePosition() {} 
   // default constructor that will also be added by the compiler
}

确保不能更改属性:

class ThePosition
{
   public int Coord1 {get; private set;}
   public int Coord2 {get; private set;}

   public ThePosition(int c1, int c2) 
   {
      Coord1 = c1; Coord2 = c2;
   } 
   // no default constructor!
}

因此,您将需要创建一个新实例来存储其他位置: current_position = new ThePosition(7,8);

class Coord()
{
   int x = 0;
   int y = 0;
   public Coord(int x,int y)
   {
     x=x;
     y=y;
   }
}

class Game()
{
    List<Coord> coords = new List<Coord>();


    public void AddCoord(Coord c)
    {
       coords.Add(c);
       if(coords.Count>maxAmount)
       {
          coords.RemoveAt(0);
       }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM