C# HashTable的一个例子.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.Specialized; using System.Collections; namespace ConsoleApplication1 //这个小程序是关于hashtable的,自己感觉就是相当于属性。 { public class Employeedata //一个员工数据类 { private string name; private decimal salary; private EmployeeID id; public Employeedata() { } public Employeedata(EmployeeID id,string name,decimal salary) { this.id = id; this.name = name; this.salary = salary; } public override string ToString() { StringBuilder sb = new StringBuilder(id.ToString(), 100); sb.Append(":"); sb.Append(string.Format("{0,-20}{1:c}",name,salary)); return sb.ToString(); } } public class EmployeeID //员工ID 类 { private string iD; public string ID { get { return iD; } set { iD = value; } } public EmployeeID(string id) { this.iD = id; } public override string ToString() { return iD.ToString(); } } public class TestHarness { public Hashtable employeses = new Hashtable(53); public void Run() { EmployeeID id1=new EmployeeID("2050"); EmployeeID id2=new EmployeeID("24210"); Employeedata myEmployee01 = new Employeedata(id1, "张三", 12613213.44m); Employeedata myEmployee02= new Employeedata(id2, "李四", 145672228883.44m); employeses.Add(id1, myEmployee01); employeses.Add(id2, myEmployee02); while (true) { try { Console.WriteLine("Enter employee ID(格式:0-9,'X'退出!):"); string userInput=Console.ReadLine(); userInput=userInput.ToUpper(); if(userInput=="X") return; EmployeeID id=new EmployeeID(userInput); DisplayData(id); } catch (Exception e) { Console.WriteLine("Exception occurred.Did you use the correct format for the employee ID?"); Console.WriteLine(e.Message); Console.WriteLine(); } Console.WriteLine(); } } public void DisplayData(EmployeeID id) { //Console.WriteLine(id.ToString()); object emObj = employeses[id]; if (emObj != null) { Employeedata employeeTemp = (Employeedata)emObj; Console.WriteLine("Employee:" + employeeTemp.ToString()); } else { Console.WriteLine("Employee not found:ID = "+id.ToString()); } } } class Program { static void Main(string[] args) { TestHarness test = new TestHarness(); //在这里本来是打算用foreach的,但是不知道杂的用不了,要用foreach 还是用ArrayList吧。 test.Run(); } } }
原文地址:https://www.cnblogs.com/fat_li/p/1833826.html