关于字典的问题
我按照PROFESSIONAL C#中的例子的思路写了一个字典的类,但是我用HASHTABLE对象怎么也无法查询,我不知道问题在哪里,下面是程序.(我在调试的时候发现HashTable对象中是有值的,而且我定义的查找键key也是能够读入用户输入信息的,但是ht[key]返回的却总是null,即使key输入存在的键值也返回null.究竟是哪里出了问题?)
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace DictionaryTest
{
class DataID
{
private string message;
public DataID(string message)
{
this.message = message;
}
public override string ToString()
{
return message;
}
public override int GetHashCode()
{
return message.GetHashCode();
}
public override bool Equals(object obj)
{
DataID rhs = obj as DataID;
if (message.Equals(rhs))
return true;
else return false;
}
}
class Data
{
private int number;
private string name;
private DataID id;
public Data(int number, string name, DataID id)
{
this.number = number;
this.name = name;
this.id = id;
}
public override string ToString()
{
return "ID:" + id.ToString() + " " + "number:" + this.number.ToString() + " " + "name:" + name;
}
}
class Program
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable(31);
DataID[] id = new DataID[10];
Data[] d = new Data[10];
for(int i = 0;i<10;i++)
{
id[i] = new DataID("Test" + i.ToString());
d[i] = new Data(i, "Name" + i.ToString(), id[i]);
ht.Add(id[i], d[i]);
Console.WriteLine(d[i].ToString());
}
Console.WriteLine("This Program is used to test hash table function.");
Console.WriteLine("Now we have already create a Hash table about data array,just input the key value of data you want to find, hash table will automatically find the matched value.");
Console.WriteLine("Hash table has " + ht.Count + " records");
while (true)
{
Console.WriteLine("Please input key.");
string input = Console.ReadLine();
if ("x" == input)
break;
DataID key = new DataID(input);
object result;
result = ht[key];
if (null == result)
Console.WriteLine("Cannot find such result!");
else
Console.WriteLine(((Data)result).ToString());
}
Console.ReadKey();
}
}
}