IEqualityComparer给出了错误的结果

时间:2014-01-10 22:49:58

标签: c# generics hashset

这是我的测试代码(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;
}
}

我不确定我哪里出错了。我已经按照一些似乎做同样事情的教程。

1 个答案:

答案 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?