废话不多说了,直接看代码
/*
* Author:hiyo585
* Company:hiyo studios
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
//Hashtable所在的命名空间为,System.Collections
//哈希表的简单知识
//哈希表的每个元素都是存储在DictionaryEntry中的键值对
namespace HashtableDemo
{
internal class Program
{
static void Main(string[] args)
{
//测试Hashtable的属性和方法
Hashtable ht = new Hashtable();
//添加元素Add
ht.Add("id", "HY585");
ht.Add("name", "Hiyo585");
ht.Add("age", "30");
//属性的应用
//Count获取其中的键值对数量
Console.Write("ht中的键值对数量为:");
Console.WriteLine(ht.Count);
//IsFixedSize
Console.Write("ht是否具有固定大小:");
Console.WriteLine(ht.IsFixedSize);
//IsReadOnly
Console.Write("ht是否为只读:");
Console.WriteLine(ht.IsReadOnly);
//IsSynchronized
Console.Write("ht是否同步访问:");
Console.WriteLine(ht.IsSynchronized);
//Creates a synchronized wrapper around the Hashtable.
Hashtable mySyncdHT = Hashtable.Synchronized(ht);
// Displays the sychronization status of both Hashtables.
Console.WriteLine("ht is {0}.", ht.IsSynchronized ? "synchronized" : "not synchronized");
Console.WriteLine("mySyncdHT is {0}.", mySyncdHT.IsSynchronized ? "synchronized" : "not synchronized");
//Item属性的使用方法
//Keys的使用方法
ht["Four"] = "David"; //添加元素
ICollection key = ht.Keys;
//获取包含哈希表中的键的ICollection
foreach (string k in key)
{
Console.WriteLine(k + ": " + ht[k]);
//ht[key]获得值
}
Console.WriteLine(0);
//Values的使用
ht["5"] = "HelloWorld";
ICollection value = ht.Values;
foreach(string v in value)
{
Console.WriteLine("value值为:" + v );
}
//Console.ReadKey();
//Remove移除指定键值的元素
Console.WriteLine("Hashtable中的元素数量:" + ht.Count);
ht.Remove("id");
Console.WriteLine("移除后的元素数量:" + ht.Count);
//Contains是否包含指定键值的元素
//ContainsKey的用法同Contains用法
Console.WriteLine("ht中包含id的元素?" + ht.Contains("id"));
Console.WriteLine("ht中包含name的元素?" + ht.Contains("name"));
//ContainsValue
Console.WriteLine("ht中包含name的元素?" + ht.ContainsValue("name"));
Console.WriteLine("ht中包含Hiyo585的元素?" + ht.ContainsValue("Hiyo585"));
//Hashtable的遍历
Console.WriteLine("\t键\t值");
foreach(DictionaryEntry de in ht)
{
Console.WriteLine("\t" + de.Key + "\t" + de.Value);
}
Console.WriteLine();
//Hashtable的遍历
ICollection ic = ht.Keys;
Console.WriteLine("\t键\t值");
foreach(string k in ic)
{
Console.WriteLine("\t" + k + "\t" + ht[k]);
}
Console.WriteLine();
//Clear()清楚所有元素
ht.Clear();
Console.WriteLine("ht中的元素数量:" + ht.Count);
Console.ReadLine();
}
}
}
/*
* id: HY585
age: 30
Four: David
name: Hiyo585
0
value值为:HY585
value值为:30
value值为:David
value值为:HelloWorld
value值为:Hiyo585
Hashtable中的元素数量:5
移除后的元素数量:4
ht中包含id的元素?False
ht中包含name的元素?True
ht中包含name的元素?False
ht中包含Hiyo585的元素?True
键 值
age 30
Four David
5 HelloWorld
name Hiyo585
键 值
age 30
Four David
5 HelloWorld
name Hiyo585
ht中的元素数量:0
*/