【案例】本案例在Student类中定义索引器,然后通过stu[i] 来引用Student类的对象实例。
【案例目的】(1)掌握索引器定义与使用。
(2)理解索引器与属性的区别。
【代码】
namespace Example1 {class Program{static void Main(string[] args){Student stu = new Student();//stu是Student类的对象名stu.Sno = "1840";stu.Name = "李四";stu[0] = 89; //stu[下标]表示类的索引器stu[1] = 90;Console.WriteLine("学生{0},学号{1}",stu.Name, stu.Sno);Console.WriteLine("他的第一门成绩是{0},第二门成绩是{1}", stu[0], stu[1]);Console.ReadLine();}}public class Student{private string sno;private string name;private double[] scores;public string Sno//属性 {set { sno = value; }get { return sno; }}public string Name{set { name = value; }get { return name; }}public Student(){scores = new double[10];} public double this[int index] //定义索引器 { get{if(index<0||index>=scores.Length ){return 0;}else{return scores[index];}}set{if (!(index < 0 || index >= scores.Length)){scores[index] = value;}}} } }
运行结果:
【索引器拓展案例与分析】