字典---Dictionary
阿新 • • 發佈:2020-10-09
=================================================EmployeeID.cs(學生編號類)
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespaceConsoleApplication7 { //作為鍵的型別必須要重寫GetHashCode() publicclassEmployeeID:IEquatable<EmployeeID> { publicstringID{get;privateset;} publicEmployeeID(strings) { ID=s; } publicoverrideboolEquals(objectobj) { if(obj==null)thrownewArgumentException("物件不能為空"); returnthis.Equals(objasEmployeeID); } publicoverrideintGetHashCode() { return1; } publicboolEquals(EmployeeIDother) { returnthis.ID==other.ID; } } }
=================================================Student.cs(學生類)
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespaceConsoleApplication7 { publicclassStudent { publicstringName{get;privateset;} publicEmployeeIDID{get;privateset;} publicStudent(EmployeeIDid,stringname) { this.Name=name; this.ID=id; } } }
=================================================主程式
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespaceConsoleApplication7 { classProgram { staticvoidMain(string[]args) { Dictionary<EmployeeID,Student>d=newDictionary<EmployeeID,Student>(); varID1=newEmployeeID("Z001"); varStu1=newStudent(ID1,"張飛"); d.Add(ID1,Stu1); varID2=newEmployeeID("Z002"); varStu2=newStudent(ID2,"關羽"); d.Add(ID2,Stu2); varID3=newEmployeeID("Z003"); varStu3=newStudent(ID3,"曹操"); d.Add(ID3,Stu3); varID4=newEmployeeID("Z004"); varStu4=newStudent(ID4,"趙雲"); d.Add(ID4,Stu4); varID5=newEmployeeID("Z005"); varStu5=newStudent(ID5,"馬超"); d.Add(ID5,Stu5); while(true) { stringstr=Console.ReadLine(); if(str.ToLower()=="exit")return; Students; EmployeeIDei=null; ei=newEmployeeID(str); if(!d.TryGetValue(ei,outs))//判斷是否存在鍵對應的相關的值 { Console.WriteLine("沒有找到該學生"); } else { Console.WriteLine(d[ei].Name); } } } } }
轉載於:https://blog.51cto.com/962410314/1548024