HashSet Contains检查的Equals(object obj)方法没有按预期的方式运行,我无法引起它的根本原因。任何帮助将不胜感激。C#HashSet Equals方法
我正在使用C#HashSet来存储类对象POS。已宣布它为
public static HashSet Store = new HashSet();
调用Store.Add(A)A正确存储在Hashset中。
当我尝试Store.Contains(B)的情况下,当GetHasCode返回相同的A和B的hascode时,调用Equals方法。我面临的问题是在Equal方法中,我从来没有得到obj A的调用。它的方式给了我obj B作为参考,因此评估为true。由于A和B的hascode是相同的,所以不应该用obj A作为参考来调用Equals?
/*的Hashset中要输入的类对象下面给出*/
public class POS
{
private int[] R = new int[Constants.MaxN];
public int prev;
/** Methods for the class goes here **/
/* To use enter the object in Hashset placed the GetHashCode and Equals functions below */
public override int GetHashCode()
{
uint val=0;
uint temp = 0;
int j = 0;
for (long i = 0; i < Globals.GetN(); i++)
{
if (i > 9) { break; }
temp = (uint)R[i];
j = (int)i * 3;
val |= (temp << j);
}
return (int) val;
}
public override bool Equals(object obj)
{
int temp, tmp;
var POSitem = obj as POS;
Console.WriteLine("Entered:");
if (obj == null) { return false; }
if (ReferenceEquals(this, POSitem)) return true;
for (int i = 0; i < Globals.GetN(); i++)
{
temp = this.Give(i);
tmp = POSitem.Give(i);
if (temp != tmp) return false;
}
return true;
}
} // end braces of POS
没关系。 'Equals'应该是对称的,自反的和传递的,因此你必须实现它,以便'a.Equals(b)== b.Equals(a)' – 2014-10-06 12:29:02
你使用的是什么版本的.NET?如果它是关于.NET 1.1的东西,那么最好实施'IEquatable'。由于泛型是安全的,因此您不必担心重写'GetHashCode()'。 –
krillgar
2014-10-06 12:29:06
@krillgar你总是必须重写'Equals'和'GetHashCode',所以如果他重写'Equals',他必须重写'GetHashCode',特别是当使用'HashSet'时。我写了一个解释[这里](http://stackoverflow.com/a/26202958/3764814)。 – 2014-10-06 12:31:01