Hashtable简单范例代码
class Student
{ public Student(string name, int age)
{ this .name = name; this .age = age; } private string name; public string Name
{ get
{ return name; } set
{ name = value ; } } private int age; public int Age
{ get
{ return age; } set
{ age = value ; } } }
class Program
{ static void Main( string[] args)
{ //仍然使用Student的类来实现, Hashtable键值对形式: key/value,相当于字典,能根据学生的姓名快速的找到对象 Student xyy = new Student( "小月月" , 14); Student fj = new Student( "凤姐" , 18); Student fr = new Student( "芙蓉姐姐" , 19); Student xl = new Student( "犀利哥" , 20); Hashtable student = new Hashtable(); student.Add( "小月月" , xyy); student.Add( "凤姐" , fj); student.Add( "芙蓉姐姐" , fr); student.Add( "犀利哥" , xl);
//student.Add("犀利哥",xl); //错误: 字典中的关键字key是不允许重复的,所以不能再添加犀利哥
//移除: 因为没有索引,所以没有RemoveAt() student.Remove( "小月月" ); //根据key来移除 student.Clear(); student.ContainsKey( "凤姐" ) ; //判断是不是含有这个键
//遍历: 因为字典没有索引,所以不能使用for来遍历,只能使用foreach
//按key遍历经常用 foreach (object key in student.Keys)
{ Student stu = student[key] as Student; Console .WriteLine(key); Console .WriteLine(stu.Age); }
//按value遍历 foreach (object value in student.Values)
{ Student stu = value as Student; if (stu != null )
{ Console .WriteLine(stu.Age); } }
//如果不按key,也不按value遍历,对字典遍历就是对字典的键值对进行遍历 foreach (DictionaryEntry de in student)
{ Console .WriteLine(de.Key); Student s = de.Value as Student; //因为得到的是object类型, 所以还需要转换才可以使用 Console .WriteLine(s.Age); }
Student s2 = student["小月月" ] as Student ; //通过姓名找到该对象 获取其他的属性 if (s2 != null )
{ Console .WriteLine(s2.Age); } Console .Read(); } }

浙公网安备 33010602011771号