本例中定义了一个Student类, 类中有一个存放5名学生成绩的数组score并初始化五个成绩{92, 83, 64, 75, 66}, 同时定义了一个索引器, 目的是封装数组score,同时在类中使用索引器的set访问器给数组score赋值,起到有条件的限制,即成绩只能在0100之间。另外,定义一个get访问器用于根据输入的学号获取对应的成绩,学号从1开始编号,范围[14]。运行样例如下图所示:
具体的代码如下所示
using System;
namespace 索引器
{
class Student
{
private int[] score = { 92, 83, 64, 75, 66 };
public int this[int index]
{
get
{
return score[index-1];
}
set
{
if (value < 0 || value > 100)
{
Console.WriteLine("学生的分数应在0到100之间");
return;
}
else
score[index - 1] = value;
}
}
}
class Program
{
static void Main(string[] args)
{
int sn = int.Parse(Console.ReadLine());//请输入查询成绩的学生学号1-5号:
//创建一个student类的实例对象st1班级1.
Student st1 = new Student();
//使用“对象[索引值]”的方式得到student类中数组score的元素值。
Console.WriteLine(st1[sn]);
//如果想给数组的元素赋值时,就使用到了set访问器,先对sn1进行判断,再赋值
int sn1 = int.Parse(Console.ReadLine());//"请输入修改成绩的学生学号1-5号:"
int score1 = int.Parse(Console.ReadLine());//请输入修改的成绩:
//赋值也使用对象【索引值】的方式
st1[sn1] = score1;
Console.WriteLine("修改后的学生成绩为:" + st1[sn1]);
}
}
}