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

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

我正在尝试创建一个列表,用于存储其中某个角色的当前位置以及之前的位置。在这段代码开始之前,字符移动了一个 column/row 并在另一种方法中更新了它的 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]}。那么当运行ning这个代码的时候,变成了{[8,7],[8,7]},本来应该是{[7,7],[8,7]}的,存了最后一个已知 current_position 和当前 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);
     
      }
 

希望这不是一个过于混乱的解释。在此先感谢您的帮助。

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

列表为{[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) 时,您并不是在添加当前 ,而是将 引用 添加到该值。

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

解决方案:更改为 "immutable" class。所以而不是

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