以下是我做练习时的一段代码,请问怎样让HashTable认为两个同值对象相等?希望高手能解决~~
using System;
namespace ConsoleApplication3
{
class Age
{
private int _year;
public Age(int year)
{
_year = year;
}
public int Year
{
get
{
return this._year;
}
}
public override bool Equals(object obj)
{
Age a = (Age)obj;
return a._year == this._year;
}
public override int GetHashCode()
{
return base.GetHashCode() ^ _year;
}
}
class Program
{
static void Main(string[] args)
{
System.Collections.Hashtable ageList = new System.Collections.Hashtable();
Age a1 = new Age(123);//其中a1和a3拥有相同的值。
ageList.Add(a1, a1);
Age a2 = new Age(567);
ageList.Add(a2,a2);
Age a3 = new Age(123);
Console.WriteLine(a1.Year);
Console.WriteLine(a3.Year);
bool boolean = a3.Equals(a1);
Console.WriteLine(boolean);
bool boolean2 = ageList.Contains(a3);
Console.WriteLine(boolean2);//两个对象的Equals()方法返回为true,但是用到HashTable中就为False了
Console.Read();
/*
* 运行结果:
* 123
* 123
* True
* False
*/
}
}
}
|