List<T>contains 方法需重写equals ,HashTable contains重写 GetHashCode原因
类结构:
public class Person
{
public String Name;
public int Id;
public Person()
{ }
public Person(String _name,int _id)
{
Name = _name;
Id = _id;
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (this.GetType() != obj.GetType())
return false;
return Equals(obj as Person);
}
private bool Equals(Person p)
{
return (this.Id == p.Id) ;
}
public override int GetHashCode()
{
return this.Id;
}
}
调用:
Person p1 = new Person("a", 34);
Person p2 = new Person("b", 45);
List<Person> listP = new List<Person>();
listP.Add(p1);
if (!listP.Contains(p2))
{
listP.Add(p2);
}
Hashtable ht = new Hashtable();
ht.Add(p1.Id, p1);
if (!ht.Contains(p2))
{
ht.Add(p2.Id, p2);