索引器:通常用来操作数组中的元素

来源:互联网 发布:apache flink hdfs 编辑:程序博客网 时间:2024/06/11 05:13

索引器

 类中保护数组对象时,可通过索引器实现方便访问

索引器用来访问类中的数组型对象元素

定义索引器与定义属性类似,一般形式为:

[修饰符] 数据类型 this[int index]

{

    get   //获取数组成员指定索引的值

        {
                return ScoreArray[index];
        }

    set  //利用外部传递的value值给 数组赋值

        {
          ScoreArray[index] = value;
        }

}

eg1:

 class Program

    {
        static void Main(string[] args)
        {
            CollClass cc = new CollClass();
            cc[0] = "CSharp";    //通过索引器给数组元素赋值
            cc[1] = "ASP.NET";
            cc[2] = "Visual Basic";
            for (int i = 0; i < CollClass.intMaxNum; i++)
            {
                Console.WriteLine(cc[i]);    //通过索引器取值
            }
            Console.ReadLine();
        }
    }
    class CollClass
    {
        public const int intMaxNum = 3;   //表示数组的长度
        private string[] arrStr;
        public CollClass()   //构造方法
        {
            arrStr = new string[intMaxNum];
        }
        public string this[int index]     //定义索引器
        {
            get
            {
                return arrStr [index ];    //通过索引器取值
            }
            set
            {
                arrStr[index] = value;    //通过索引器赋值
            }
        }
    }

eg2:

编程:

定义一个Student类,包含学号和姓名两个字段,并定义一个班级类ClassList,包含一个具有5个元素Student数组对象,利用索引器访问该数组对象,

并在主函数中 访问。

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace _2

{

    class Student

    {

        public int ID;

        public string name;

        public Student(int ID,string name)

        {

            this.ID = ID;

            this.name = name;

        }

        public void show()

        {

            Console.WriteLine("{0} {1}",ID ,name );

        }

    }

    class ClassList

    {

        Student[] my = new Student[5];

        public Student  this[int index]

        {

            get

            {

                if (index < 0 || index >= my.Length)

                {

                    return null;

                }

                return my[index];

            }

            set

            {

                if (index < 0 || index >= my.Length)

                {

                    return;

                }

                my[index] = value;

            }

        }

    }

    public class MainClass

    {

        public static void Main()

        {

            ClassList n = new ClassList();

            n[0] = new Student(1,"张三1");

            n[1] = new Student(2, "张三2");

            n[2] = new Student(3, "张三3");

            n[3] = new Student(4, "张三4");

            n[4] = new Student(5, "张三5");

            for (int i = 0; i <5; i++)

            {

                Student my = (Student)n[i];

                my.show();//通过下标获取对象中数组成员的只

            }

           Console.ReadLine();

        }

    } 

}

 

 

 

 

 

 

 

0 0
原创粉丝点击