Hashtable 類的實用方法。
(1).Count 屬性存儲着散列表內元素的數量,它會返回一個整數。
(2).Clear 方法可以立刻從散列表中移除所有元素。
(3).Remove 方法會取走關鍵字,而且該方法會把指定關鍵字和相關聯的數值都移除。
(4).ContainsKey 方法查看該元素或者數值是否在散列表內。
3.Hashtable 的應用程序。程序首先從一個文本文件中讀入一系列術語和定義。這個過程是在子程序BuildGlossary 中編碼實現的。文本文件的結構是:單詞,定義,用逗號在單詞及其定義之間進行分隔。這個術語表中的每一個單詞都是單獨一個詞,但是術語表也可以很容易地替換處理短語。這就是用逗號而不用空格作分隔符的原因。此外,這種結構允許使用單詞作爲關鍵字,這是構造這個散列表的正確方法。另一個子程序DisplayWords 把單詞顯示在一個列表框內,所以用戶可以選取一個單詞來獲得它的定義。既然單詞就是關鍵字,所以能使用Keys 方法從散列表中正好返回單詞。然後,用戶就可以看到有定義的單詞了。用戶可以簡單地點擊列表框中的單詞來獲取其定義。用Item 方法就可以取回定義,並且把它顯示在文本框內。
// 吳新強 實驗小結 2013年3月16日22:00:45
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
- using System.Collections;
- using System.IO ;
- namespace WindowsApplication3
- {
- public partial class Form1 : Form
- {
- private Hashtable glossary = new Hashtable();
- public Form1()
- {
- InitializeComponent();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- BuildGlossary(glossary);
- DisplayWords(glossary);
- }
- private void BuildGlossary(Hashtable g)
- {
- StreamReader inFile;
- string line;
- string[] words;
- inFile = File.OpenText(@"c:\words.txt ");
- char[] delimiter = new char[] { ',' };
- while (inFile.Peek() != -1)
- {
- line = inFile.ReadLine();
- words = line.Split(delimiter);
- g.Add(words[0], words[1]);
- }
- inFile.Close();
- }
- private void DisplayWords(Hashtable g)
- {
- Object[] words = new Object[100];
- g.Keys.CopyTo(words, 0);
- for (int i = 0; i <= words.GetUpperBound(0); i++)
- if (!(words[i] == null))
- lstWords.Items.Add((words[i]));
- }
- private void lstWords_SelectedIndexChanged(object sender, EventArgs e)
- {
- Object word;
- word = lstWords.SelectedItem;
- txtDefinition.Text = glossary[word].ToString();
- }
- }
- }