实现了GetHashCode但是Dictionary无法找到密钥?

时间:2012-12-29 07:03:59

标签: c# dictionary gethashcode iequatable

在我的课堂上,我实施了EqualsGetHashCode。但当我在C#代码中将它用作字典的键时,我收到错误:"Key not found exception" 谢谢,

public class Time: IEquatable<Time>
{
    public String hour;
    public String minute;

    public Time()
    {
        hour = "00";
        minute = "00";
    }

    public Time(String hour, String minute)
        : this()
    {
        this.hour = hour;
        this.minute = minute;
    }

    public override int GetHashCode()
    {
        int hash = int.Parse(hour) * 60 + int.Parse(minute);
        return hash.GetHashCode();
    }
    public override bool Equals(Time time)
    {

            return (this.hour == time.hour && this.minute == time.minute);

    }

}

我正在使用它的代码:

Dictionary<Time, int> time2RowIndex = new Dictionary<Time, int>();

...

int beginRow = 0;
if(time2RowIndex.ContainsKey(time.hour))
      beginRow = time2RowIndex [time.hour];

1 个答案:

答案 0 :(得分:5)

试试这个。诀窍是从对象(和Equals)覆盖GetHashCode,而不是仅仅实现IEquatable<>

此外,如果Hour对象上的MinuteTimeTime的实例添加到词典之后发生了更改,则该桶(由哈希代码选择)添加的时间将不再匹配对象上的哈希码。这意味着即使你向字典提供一个具有相同价值的对象(比如ContainsKey),它也不会在字典中找到原始项目(因为它将查看的哈希桶并不是&#39 ; t包含原始对象)。最佳做法是GetHashCode函数中引用的所有字段都是只读的,以避免出现这些情况。

public class Time : IEquatable<Time>
{
    public String Hour;
    public String Minute;

    public Time()
    {
        Hour = "00";
        Minute = "00";
    }

    public Time(String hour, String minute)
        : this()
    {
        this.Hour = hour;
        this.Minute = minute;
    }

    public override int GetHashCode()
    {
        return int.Parse(Hour) * 60 + int.Parse(Minute);
    }

    public override bool Equals(object obj)
    {
        var time = obj as Time;
        return !ReferenceEquals(time, null) && Equals(time);
    }

    public bool Equals(Time time)
    {
        return string.Equals(Hour, time.Hour, StringComparison.Ordinal) && string.Equals(Minute, time.Minute, StringComparison.Ordinal);
    }
}