3

在我的课堂上,我已经实现了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];
4

1 回答 1

5

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

此外,如果HourMinuteTime的实例Time添加到字典后对象发生更改,则存储桶(在添加时由哈希码选择)将不再匹配对象上的哈希码。这意味着即使您向字典提供一个相等值的对象(例如使用ContainsKey),它也不会在字典中找到原始项目(因为它将查找的哈希桶不包含原始对象)。最佳实践是函数中引用的所有字段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);
    }
}
于 2012-12-29T07:17:51.153 回答