这是我的测试代码(Contains在应该的时候没有返回true):
HashSet<TilePosition> test = new HashSet<TilePosition>(new TilePositionCompare());
test.Add(new TilePosition(10,10));
if (test.Contains(new TilePosition(10,10)))
Debug.Log("We should see this");
我的比较课程: 使用System.Collections.Generic;
public class TilePositionCompare : IEqualityComparer<TilePosition>
{
public bool Equals(TilePosition tileA, TilePosition tileB)
{
return tileA.PosX == tileB.PosX && tileA.PosY == tileB.PosY;
}
public int GetHashCode(TilePosition tile)
{
return tile.GetHashCode();
}
}
这是我要比较的课程:
using System.Collections;
public class TilePosition
{
int posX;
int posY;
public TilePosition (int posX, int posY)
{
this.posX = posX;
this.posY = posY;
}
}
我不确定我哪里出错了。我已经按照一些似乎做同样事情的教程。
答案 0 :(得分:4)
GetHashCode()
应基于X / Y.
public class TilePositionCompare : IEqualityComparer<TilePosition>
{
public bool Equals(TilePosition tileA, TilePosition tileB)
{
return tileA.PosX == tileB.PosX && tileA.PosY == tileB.PosY;
}
public int GetHashCode(TilePosition tile)
{
var hash = 17;
hash = hash * 23 + tile.PosX.GetHashCode();
hash = hash * 23 + tile.PosY.GetHashCode();
return hash;
}
}
从https://stackoverflow.com/a/263416/70386
采用的示例要知道为什么使用奇素数(17),请在此处阅读:Why does Java's hashCode() in String use 31 as a multiplier?