C#索引器

来源:互联网 发布:让子弹飞 隐喻 知乎 编辑:程序博客网 时间:2024/06/10 22:11
索引器是一种特殊的类成员,它能够让对象以类似数组的方式来存取,使程序看起来更为直观,更容易编写。
C#中的类成员可以是任意类型,包括数组或集合。当一个类包含了数组或集合成员时,索引器将大大简化对数组或集合成员的存取操作。
索引器定义形式如下:
[修饰符] 数据类型 this[索引类型 index]
{
       Get{//获得属性的代码}
       Set{//设置属性的代码}
}

数据类型表示将要存取的数组或集合元素的类型;索引类型表示该索引器使用哪一种类型的索引来存取数组或集合元素,可以是整数,也可以是字符串;this表示操作本对象的数组或集合成员,可以简单把它理解成索引器的名字,因此索引器不能具有用户定义的名称。
接口中的索引器
接口中的索引器与类索引器的区别有两个:
      一、接口索引器不使用修饰符;
      二、接口索引器只包含访问器get或set,没有实现语句。
      例如:
      Public interface IStudents
      {
             Student this[int index]{get;set}
       }
索引器综合代码演示:
  //声明一个接口
    public interface IStudents
    {
        Student this[int index] { get; set; }  //声明索引器
    }
    //创建一个学生类
    public class Student
    {
        public string name;
        public int no;
        public Student(string n, int num)
        {
            name = n;
            no = num;
        }
    }
    //创建一个学生集合
    public class Students : IStudents   //从接口派生
    {
        Student[] s = new Student[100];  //学生集合
        public Student this[int i]       //实现接口中的索引器
        {
            get
            {
                if (i > 0 && i < s.Length)
                    return s;
                else
                    return s[0];
            }
            set
            {
                if (i > 0 && i < s.Length)
                    s = value ;
                else
                    s[0] = value ;
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //创建学生集合对象
            Students stus = new Students();
            //通过索引器写入学生的数据
            stus[0] = new Student("tom", 101);
            stus[1] = new Student("david", 102);
            stus[2] = new Student("lily", 103);
            for (int i = 0; i < 3; i++)
            {
                //通过索引器输出学生的数据
                Console.WriteLine("姓名:{0} 学号:{1}", stus.name, stus.no);
            }
            Console.ReadKey();
        }
    }
原创粉丝点击