【发布时间】:2015-12-15 09:03:31
【问题描述】:
我正在尝试将Definition 类型的两个哈希集与EqualityComparer<T>.Default.Equals(value, oldValue) 进行比较。 Definition 定义如下
public class Definition
{
public string Variable { get; set; }
public HashSet<Location> LocationList { get; set; }
public override bool Equals(object obj)
{
Definition other = obj as Definition;
return other.Variable.Equals(this.Variable) && other.LocationList!= null &&this.LocationList != null
&& other.LocationList.Count == this.LocationList.Count
&& other.LocationList == this.LocationList;
}
public override int GetHashCode()
{
return this.Variable.GetHashCode() ^ this.LocationList.Count.GetHashCode();// ^ this.LocationList.GetHashCode();
}
}
public class Location
{
public int Line { get; set; }
public int Column { get; set; }
public int Position { get; set; }
public string CodeTab { get; set; }
public Location(int line, int col, int pos, string tab)
{
Line = line;
Column = col;
Position = pos;
CodeTab = tab;
}
public override bool Equals(object obj)
{
Location other = obj as Location;
return this.CodeTab == other.CodeTab
&& this.Position == other.Position
&& this.Column == other.Column
&& this.Line == other.Line;
}
public override int GetHashCode()
{
return this.CodeTab.GetHashCode() ^ this.Position.GetHashCode()
^ this.Column.GetHashCode() ^ this.Line.GetHashCode();
}
}
不知何故,对于类似的集合,结果返回为false,尽管所有信息都保持不变。唯一的区别是某些元素的位置是互换的,但我知道HashSet 在比较时不会保留或检查顺序。谁能告诉我这里出了什么问题?
PS:我也尝试取消注释this.LocationList.GetHashCode(),但没有成功。
【问题讨论】:
-
这是
HashSet<Location>不是HashSet<Definition>,但您声明要比较“定义的两个哈希集”。所以要么你的问题问错了,要么你的代码做了不同的事情。 -
value和oldValue是Definition类型。
标签: c# hashset iequalitycomparer