using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace Hashtable1
{
//添加一个学生类
class Student
{
/// <summary>
/// 无参构造函数
/// </summary>
public Student()
{ }
/// <summary>
/// 有参构造函数
/// </summary>
/// <param name="name"></param>
/// <param name="age"></param>
public Student(string name, int age)
{
this.name = name;
this.age = age;
}
/// <summary>
/// 姓名
/// </summary>
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
/// <summary>
/// 年龄
/// </summary>
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
}
class Program
{
static void Main(string[] args)
{
// 创建几个学生
Student xyy = new Student("小月月",16);
Student fj = new Student("凤姐", 16);
Student fr = new Student("芙蓉姐姐", 16);
Student xl = new Student("犀利哥", 16);
// 创建一个键和值的集合,并将创建的学生添加到集合中
Hashtable ht = new Hashtable();
ht.Add("小月月",xyy);
ht.Add("凤姐",fj);
ht.Add("芙蓉姐姐",fr);
ht.Add("犀利哥",xl);
//通过Key遍历集合中的数据
foreach (object key in ht.Keys)
{
Student stu = ht[key] as Student;
if (stu != null)
{
//输出姓名
//Console.WriteLine(stu.Name);
}
//Console.WriteLine(key);
}
//通过Value获取数据
foreach (object value in ht.Values)
{
Student stu = value as Student;
if (stu != null)
{
//输出姓名
//Console.WriteLine(stu.Name);
}
//Console.WriteLine(value);
}
//通过字典获取数据
foreach (DictionaryEntry val in ht)
{
Student stu = val.Value as Student;
if (stu != null)
{
Console.WriteLine(stu.Name);
}
//Console.WriteLine(val.Value);
}
Console.Read();
}
}
}