代码之家  ›  专栏  ›  技术社区  ›  Mansa

c#包含不工作的对象

  •  2
  • Mansa  · 技术社区  · 7 年前

    我试图在列表之间创建一个检查,但运气不好:-/

    我有一个有100个字段的游戏板,通过循环只将空字段添加到新列表中:

    for(int i = 0; i < thisGame.boardFields.Count; i++)
    {
        if (thisGame.boardFields.Count != 0 && thisGame.boardFields [i] != null) 
        {
            BoardField thisField = thisGame.boardFields [i];
            if (thisField.owner == "0" && thisField.number != 13) 
            {
                Tile tTile = new Tile();
                tTile.color = thisField.color;
                tTile.number = thisField.number.ToString();
    
                tempBoard.Add (tTile);
            }
        }
    }
    

    for (var i = 0; i < thisGame.playerTiles.Count; i++)
    {    
        Tile tempTile = new Tile();
        tempTile.color = thisGame.playerTiles[i].color;
        tempTile.number = thisGame.playerTiles[i].number.ToString();
    
        if (!tempBoard.Contains (tempTile)) 
        {
            testTile = tempTile;
            print ("HUSTON WE HAVE A PROBLEM: " + tempTile.color + "-" + tempTile.number);
        }    
    }
    

    这是平铺类的定义:

    public class Tile 
    {    
        public int id;
        public string color;
        public string number;   
    }
    

    现在我的问题是,它每5个瓷砖打印在球员瓷砖列表?玩家互动程序列表中的所有互动程序都可以在 tempBoard 列表

    希望提前得到帮助和感谢:-)

    2 回复  |  直到 7 年前
        1
  •  7
  •   Gilad Green Fábio    7 年前

    工作 Contains 需要检查两个对象之间的相等性。默认情况下,对于引用类型,它通过检查引用相等性来实现。因此,拥有两个相同类型的不同实例(内存中的对象),并且所有属性的值都相同,仍然会导致它们不相等,并且对于 包含

    1. Equals GetHashCode 对象的方法。关于重写方法的参考:

    2. IEquatable<Tile> 接口,然后使用重载:

      list.Contains(searchedTile, new SomeClassImplementingInterface());
      

      Id在重写 方法 是非平凡的(不包括类的所有属性),或者如果您无法控制 Tile

    3. 使用linq Any 方法:

      collection.Any(item => item.number == tempTile.number && item.color == temTile.color);
      

    此外,使用 object initializer syntax

    Tile tTile = new Tile
    { 
        color = thisField.color,
        number = thisField.number.ToString()
    }
    

    public 它们可能应定义为属性:

    public class Tile 
    {
        public int Id { get; set; }
        public string Color { get; set; }
        public string Number { get; set; }
    }
    

    最后看看 naming conventions for C#

        2
  •  0
  •   Becca    7 年前

    根据这个堆栈溢出答案( https://stackoverflow.com/a/9264597/1102726 IEquatable. Equals , Contains tempTile ,它会 永远不要在那个名单上。您可以在的定义中提供该覆盖 Tile Contains(tempTile) 比如说 tempBoard.Any(t => t.number == tempTile.number) 或者,无论您如何定义两个相同的平铺。