gpt4 book ai didi

c# 包含对象不工作

转载 作者:太空宇宙 更新时间:2023-11-03 20:59:55 24 4
gpt4 key购买 nike

我正在尝试在列表之间创建一个检查,但我没有运气:-/

我有一个包含 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);
}
}
}

然后我循环遍历玩家 5 个方 block 以查看玩家是否有不可玩的方 block ,例如具有相同对象的空字段不可用,如下所示:

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

这是 Tile 类的定义:

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

现在我的问题是,它会打印在玩家板 block 列表中的每 5 个板 block 上吗? tempBoard 列表中播放器瓷砖列表中的所有瓷砖是否可用?

我想念她什么?

希望得到帮助并提前致谢:-)

最佳答案

上类Contains需要检查两个对象之间的相等性。默认情况下,对于引用类型,它通过检查引用相等性来实现。因此,具有相同类型且对所有属性具有相同值的两个不同实例(内存中的对象)仍将导致它们不相等,并且对于Contains。返回 false。

要克服这 3 个选项:

  1. 你需要你的类来覆盖 EqualsGetHashCode对象的方法。关于覆盖方法的引用:

  2. 替代覆盖类中方法的另一种选择是创建一个实现 IEquatable<Tile> 的类。接口(interface),然后使用重载:

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

    我用它来防止 Equals 被覆盖/GetHashCode是非常重要的(不包括该类的所有属性)或者如果您无法控制 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#

关于c# 包含对象不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46515341/

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