在我的课堂上,我实施了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];
答案 0 :(得分:5)
试试这个。诀窍是从对象(和Equals
)覆盖GetHashCode
,而不是仅仅实现IEquatable<>
。
此外,如果Hour
对象上的Minute
或Time
在Time
的实例添加到词典之后发生了更改,则该桶(由哈希代码选择)添加的时间将不再匹配对象上的哈希码。这意味着即使你向字典提供一个具有相同价值的对象(比如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);
}
}