[英]Can I implement a base GetHashCode() that will work for all extensions of my abstract base class?
[英]Can I Implement GetHashCode for my custom Collection
我有一個自定義集合,如下所示
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?
這與線路有關:
if (!collection.Contains(value, cmp))
對矢量或序列的測試(因為它看起來像Enumerable.Contains
)在調用GetHashCode()
沒有任何意義; 如果數據已被分組為散列桶或其他一些優化結構,那么這很有用,但這里的數據只是一個平坦的值序列。 如果它需要調用一個方法,它也可以調用Equals
而不是GetHashCode()
,因為如果哈希是相同的,它仍然需要調用Equals
(哈希碼表示不相等,但不能表示相等)。 因此,它是一種選擇恰好調用每個對象一個方法的,VS每個對象的至少一種方法,並且每個對象的可能的兩種方法。 第一個顯然是可取的。
如果數據是Dictionary<Person, ...>
或HashSet<Person>
,那么我希望使用GetHashCode()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.