У меня есть пользовательская коллекция, как показано ниже
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?
Equals(...)
что произойдет, если оба имени пусты? Должны ли они считаться равными? Или должно быть выброшено исключение. - person Richard   schedule 07.03.2013return p1.Name == p2.Name
- работа сделана и никаких проблем сnull
. Также; вы можете подумать, что произойдет, если иx
, иy
равныnull
. Большинство людей ожидает, чтоreturn true;
- person Marc Gravell   schedule 07.03.2013Stack<T>
класс уже. И почему вы на самом деле хотите, чтобыGetHashCode
называли? - person Groo   schedule 07.03.2013Person
, объявите его какPersonComparer : IEqualityComparer<Person>
. То, что вы делаете сейчас, не имеет смысла (используя дженерики, а затем приведение к определенному классу). - person Groo   schedule 07.03.2013GetHashCode
противEquals
улучшает производительность. Он использует структуру данных (например,Dictionary
), которая может использоватьGetHashCode
для сужения области поиска. В вашем случае вы используетеArray.Contains
, что требует временной сложностиO(n)
(он повторяет все элементы). Вы, вероятно, получите гораздо лучшее предложение, если напишите, что вы на самом деле пытаетесь сделать с этой структурой. Вы уверены, что эта структура должна работать как стек (LIFO)? - person Groo   schedule 07.03.2013