zoukankan      html  css  js  c++  java
  • 索引器

    //类

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

  • 相关阅读:
    C++ new 解析重载 .
    __cdecl,__fastcall, __stdcall 什么区别? .
    C++构造函数调用顺序
    用gdb调试core dump文件
    placement new(转)
    [精华] 跟我一起写 Makefile
    使用 GDB 调试多进程程序
    第37条:避免对函数中继承得来的默认参数值进行重定义
    程序只运行一个是实例 .
    南通SEO:单页的SEO元素
  • 原文地址:https://www.cnblogs.com/danmao/p/3871781.html
Copyright © 2011-2022 走看看