在我的课堂上,我实现了Equals
和GetHashCode
。但是,当我将其用作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];
最佳答案
尝试这个。诀窍是从对象(和Equals
)覆盖GetHashCode
,而不仅仅是实现IEquatable<>
。
同样,如果在将Hour
的实例添加到字典后Minute
对象上的Time
或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);
}
}