上面的代碼 ,我們重點看下GetHashCode()方法,我們前面講了, 如果要實現散列算法,必須滿足很多苛刻的要求.但是我們知道string類可以直接 作為Hashtable的key類,說明Microsoft已經為string類提供了很有效的散列算法 .所以我們直接應用string.GetHashCode()去重寫我們的EmployeeID類的 GetHashCode()方法.當然性能可能會有損失,因為EmployeeID類轉換為string的 時候會損失性能.
EmployeeData類就沒有什麼特別的啦,就一些數據
EmployeeData類
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/**//// <summary>
/// Summary description for EmployeeData
/// </summary>
public class EmployeeData
{
public EmployeeData()
{
//
// TODO: Add constructor logic here
//
}
public EmployeeData(string name,string age,string gender)
{
this.Name = name;
this.Age = age;
this.Gender = gender;
}
public string Name { get; set; }
public string Age { get; set; }
public string Gender { get; set; }
}
Main 測試代碼
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace HashTableTest
{
class Program
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht.Add(new EmployeeID("A0001"), new EmployeeData ("Johnny", "24", "Man"));
ht.Add(new EmployeeID("A0002"), new EmployeeData ("Vicky", "20", "female"));
ht.Add(new EmployeeID("A0003"), new EmployeeData ("Allen", "30", "male"));
Console.WriteLine("Please input the Employee ID");
string userId = Console.ReadLine();
//當 輸入ID的是否,返回員工的詳細數據
EmployeeData E1 = (EmployeeData)ht[new EmployeeID(userId)];
if (E1 != null)
{
Console.WriteLine ("Employee " + userId+"Data is :");
Console.WriteLine(E1.Name);
Console.WriteLine(E1.Age);
Console.WriteLine (E1.Gender);
}
Console.ReadLine ();
}
}
}
結果如圖所示