首页 > 代码库 > 索引器

索引器

//类

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);
        }
    }