我有一个自定义集合,如下所示
public class CustomCollection<T>:IEnumerable<T>, IEnumerator<T>
{
int size = 0;
int current = 0;
int position = -1;
CustomComparer<T> cmp = new CustomComparer<T>();
T[] collection = null;
public CustomCollection(int sizeofColl)
{
size = sizeofColl;
collection = new T[size];
}
public void Push(T value)
{
if (!collection.Contains(value, cmp))
collection[current++] = value;
}
public T Pop()
{
return collection[--current];
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return (IEnumerator<T>)this;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
public T Current
{
get { return collection[position]; }
}
public void Dispose()
{
}
object System.Collections.IEnumerator.Current
{
get { throw new NotImplementedException(); }
}
public bool MoveNext()
{
position++;
if (position >= collection.Length)
return false;
else
return true;
}
public void Reset()
{
throw new NotImplementedException();
}
}
现在我想要一个Person类的集合,如下所示,以及IEqualityComparer
public class Person
{
public string Name { get; set; }
public int ID { get; set; }
}
public class CustomComparer<T>:IEqualityComparer<T> {
public bool Equals(T x, T y)
{
Person p1 = x as Person;
Person p2 = y as Person;
if (p1 == null || p2 == null)
return false;
else
return p1.Name.Equals(p2.Name);
}
public int GetHashCode(T obj)
{
Person p = obj as Person;
return p.Name.GetHashCode();
}
}
现在,当我对集合执行以下操作时,为什么只调用Equals方法而不是GetHashCode()?
CustomCollection.CustomCollection<Person> custColl = new CustomCollection<Person>(3);
custColl.Push(new Person() { Name = "per1", ID = 1 });
custColl.Push(new Person() { Name = "per2", ID = 2 });
custColl.Push(new Person() { Name = "per1", ID = 1 });
或者如何让我的代码调用GetHashCode? p>
答案 0 :(得分:2)
这与行:
有关if (!collection.Contains(value, cmp))
针对向量或序列的测试(因为它看起来像Enumerable.Contains
)在调用GetHashCode()
时没有任何意义;如果数据已被分组为散列桶或其他一些优化结构,那么这很有用,但这里的数据只是一个平坦的值序列。如果需要调用某个方法,也可以调用Equals
而不是GetHashCode()
,因为如果哈希值相同,仍然需要调用Equals
(哈希码表示不相等,但不能表示相等)。因此,每个对象调用完全一个方法,vs 每个对象至少一个方法,每个对象可能有两个方法。第一个显然是可取的。
如果数据是Dictionary<Person, ...>
或HashSet<Person>
,那么我希望GetHashCode()
可以使用。