26.HashTable类
HashTable 类:
该类实现一个哈希表,该哈希表将键映射到相应的值。任何非 null 对象都可以用作键或值。
1、HashTable 通常称为哈希表;
2、根据(Key)可以查找到相应的值(Value);
3、需要引用命名空间 System.Collections;
一、应用如下:
1 class Program 2 { 3 void Test() 4 { 5 Hashtable ht = new Hashtable(); 6 ht.Add("liu", "现在是刘先生的个人信息"); 7 ht.Add("zhang", "现在是张先生的个人信息"); 8 ht.Add("wang", "现在是王先生的个人信息"); 9 ht.Add("lu", "现在是卢先生的个人信息"); 10 11 //查找 12 //Console.WriteLine(ht["lu"]); 13 14 //遍历(遍历所有的“键”,输出“键”) 15 foreach (var item in ht.Keys) 16 { 17 Console.WriteLine(item); 18 } 19 //遍历(遍历所有的“值”,输出“值”) 20 foreach (var item in ht.Values) 21 { 22 Console.WriteLine(item); 23 } 24 } 25 static void Main(string[] args) 26 { 27 Program b = new Program(); 28 b.Test(); 29 Console.ReadKey(); 30 } 31 }
二、HashTable常用形式:
1 namespace ProgramTast1 2 { 3 /// <summary> 4 /// 定义Person类,初始化字段 5 /// </summary> 6 public class Person 7 { 8 private string _strName; 9 private int _intHeight; 10 private int _intWeight; 11 12 //构造函数 13 public Person(string name,int height,int weight) 14 { 15 _strName = name; 16 _intHeight = height; 17 _intWeight = weight; 18 } 19 //属性 20 public string StrName 21 { 22 get 23 { 24 return _strName; 25 } 26 27 set 28 { 29 _strName = value; 30 } 31 } 32 33 public int IntHeight 34 { 35 get 36 { 37 return _intHeight; 38 } 39 40 set 41 { 42 _intHeight = value; 43 } 44 } 45 46 public int IntWeight 47 { 48 get 49 { 50 return _intWeight; 51 } 52 53 set 54 { 55 _intWeight = value; 56 } 57 } 58 } 59 /// <summary> 60 /// 应用键值对调用对象 61 /// </summary> 62 class Program 63 { 64 void Test() 65 { 66 Hashtable ht = new Hashtable(); 67 68 //实例化对象 69 Person per1 = new Person("刘先生", 175, 60); 70 Person per2 = new Person("张先生", 185, 80); 71 Person per3 = new Person("王先生", 165, 65); 72 Person per4 = new Person("卢先生", 190, 70); 73 74 //一般“键”为字符串;“值”为对象。输入字符串显示对象 75 ht.Add("liu", per1); 76 ht.Add("zhang", per2); 77 ht.Add("wang", per3); 78 ht.Add("lu", per4); 79 80 //遍历(遍历所有的“值”) 81 foreach (Person perObj in ht.Values) 82 { 83 Console.WriteLine(); 84 Console.WriteLine(perObj.StrName); 85 Console.WriteLine(perObj.IntHeight); 86 Console.WriteLine(perObj.IntWeight); 87 } 88 } 89 static void Main(string[] args) 90 { 91 Program b = new Program(); 92 b.Test(); 93 Console.ReadKey(); 94 } 95 } 96 }