//類
class Student
??? {
??????? public int StuNo { get; set; }
??????? public string StuName { get; set; }
??????? public int StuAge { get; set; }
??? }
//索引器
?class MyClass
??? {
??????? //存儲5個學員信息的數組
??????? public Student[] students = new Student[5];
??????? public MyClass()
??????? {
??????????? students[0] = new Student() { StuNo = 1001, StuName = "張三", StuAge = 23 };
??????????? students[1] = new Student() { StuNo = 1002, StuName = "李四", StuAge = 24 };
??????????? students[2] = new Student() { StuNo = 1003, StuName = "王五", StuAge = 25 };
??????????? students[3] = new Student() { StuNo = 1004, StuName = "趙六", StuAge = 26 };
??????????? students[4] = new Student() { StuNo = 1005, StuName = "小七", StuAge = 27 };
??????? }
??????? /// <summary>
??????? /// 學號索引器
??????? /// </summary>
??????? /// <param name="stuNo"></param>
??????? /// <returns></returns>
??????? public Student this[int stuNo]
??????? {
??????????? get
??????????? {
??????????????? foreach (Student item in students)
??????????????? {
??????????????????? if (item.StuNo == stuNo)
??????????????????? {
??????????????????????? return item;
??????????????????? }
??????????????? }
??????????????? return null;
??????????? }
??????? }
??????? /// <summary>
??????? /// 姓名索引器
??????? /// </summary>
??????? /// <param name="stuName"></param>
??????? /// <returns></returns>
??????? public Student this[string stuName]
??????? {
??????????? get
??????????? {
??????????????? foreach (var item in students)
??????????????? {
??????????????????? if(item.StuName == stuName)
??????????????????? {
??????????????????????? return item;
??????????????????? }
??????????????? }
??????????????? return null;
??????????? }
??????? }
??? }
//使用
class Program
??? {
??????? static void Main(string[] args)
??????? {
??????????? MyClass myClass = new MyClass();
??????????? Student stu = myClass[1002];
??????????? Console.WriteLine("學號:" + stu.StuNo + " 姓名:" + stu.StuName + " 年齡:" + stu.StuAge);
??????????? Student stu2 = myClass["小七"];
??????????? Console.WriteLine("學號:" + stu2.StuNo + " 姓名:" + stu2.StuName + " 年齡:" + stu2.StuAge);
??????? }
??? }
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
