您好,登錄后才能下訂單哦!
=================================================EmployeeID.cs(學生編號類)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication7 { //作為鍵的類型必須要重寫GetHashCode() public class EmployeeID : IEquatable<EmployeeID> { public string ID { get; private set; } public EmployeeID(string s) { ID = s; } public override bool Equals(object obj) { if (obj == null) throw new ArgumentException("對象不能為空"); return this.Equals(obj as EmployeeID); } public override int GetHashCode() { return 1; } public bool Equals(EmployeeID other) { return this.ID == other.ID; } } }
=================================================Student.cs(學生類)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication7 { public class Student { public string Name { get; private set; } public EmployeeID ID { get; private set; } public Student(EmployeeID id, string name) { this.Name = name; this.ID = id; } } }
=================================================主程序
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication7 { class Program { static void Main(string[] args) { Dictionary<EmployeeID, Student> d = new Dictionary<EmployeeID, Student>(); var ID1 = new EmployeeID("Z001"); var Stu1 = new Student(ID1, "張飛"); d.Add(ID1, Stu1); var ID2 = new EmployeeID("Z002"); var Stu2 = new Student(ID2, "關羽"); d.Add(ID2, Stu2); var ID3 = new EmployeeID("Z003"); var Stu3 = new Student(ID3, "曹操"); d.Add(ID3, Stu3); var ID4 = new EmployeeID("Z004"); var Stu4 = new Student(ID4, "趙云"); d.Add(ID4, Stu4); var ID5 = new EmployeeID("Z005"); var Stu5 = new Student(ID5, "馬超"); d.Add(ID5, Stu5); while (true) { string str = Console.ReadLine(); if (str.ToLower() == "exit") return; Student s; EmployeeID ei = null; ei = new EmployeeID(str); if (!d.TryGetValue(ei, out s))//判斷是否存在鍵對應的相關的值 { Console.WriteLine("沒有找到該學生"); } else { Console.WriteLine(d[ei].Name); } } } } }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。