您的位置:首页 > 产品设计 > UI/UE

Hashtable 类的实用方法 BuildGlossary方法

2013-03-16 21:55 232 查看
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();
}
}
}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: