【发布时间】:2018-07-21 13:55:50
【问题描述】:
我想创建一个Dictionary<Coordinate, Status>,但密钥始终等于"Bot.Core.Games.Coordinate"。
类
坐标
public class Coordinate
{
public int x { get; set; }
public int y { get; set; }
}
状态
public class Enums
{
public enum Status { UNCAPTURED, PLAYER1, PLAYER2, WIN }
}
第一次尝试
Dictionary<Coordinate, Status> Fields { get; set; } = new Dictionary<Coordinate, Status>()
{
{new Coordinate() { x = 0, y = 0 }, Status.UNCAPTURED}
}
第二次尝试
我做了一些研究,发现了这个:Use custom object as Dictionary Key
所以代码现在看起来像这样:
public class Coordinate
{
public int x { get; set; }
public int y { get; set; }
public bool Equals(Coordinate coordinate) => coordinate.x.Equals(x) && coordinate.y.Equals(y);
public bool Equals(object o) => Equals(o as Coordinate);
public override int GetHashCode() => x.GetHashCode() ^ y.GetHashCode();
}
第三次尝试
由于之前尝试过的代码都不起作用,我做了更多研究,发现this。
所以现在代码是:
public class Coordinate
{
public int x { get; set; }
public int y { get; set; }
public class CoordinateEqualityComparer : IEqualityComparer<Coordinate>
{
public bool Equals(Coordinate a, Coordinate b) => ((a.x == b.x) & (a.y == b.y));
public int GetHashCode(Coordinate obj)
{
string combined = obj.x + "|" + obj.y;
return (combined.GetHashCode());
}
}
}
Dictionary<Coordinate, Status> Fields { get; set; } = new Dictionary<Coordinate, Status>(new Coordinate.CoordinateEqualityComparer())
{
{new Coordinate() { x = 0, y = 0 }, Status.UNCAPTURED}
}
密钥始终是"Bot.Core.Games.Coordinate"。如何解决这个问题?
【问题讨论】:
-
它没有,您只是对调试器告诉您的内容感到困惑。覆盖 ToString() 使其看起来更好。
-
@HansPassant 但它也会抛出 KeyNotFoundException。
-
(a.x == b.x) & (a.y == b.y)应该是(a.x == b.x) && (a.y == b.y)吗? -
为什么
Status在另一个类(Enums)中? -
@Camilo Terevinto:& 和 && 对布尔操作数进行操作时的区别在于 && 是短路的,而 & 不是(即,即使第一个是假的)。谁知道!?大约 5 年前,Eric Lippert 在他博客上的反馈评论中向我指出了这一点。这就像VB中And和AndAlso的区别。再次感谢埃里克。
标签: c#