今天,抽空又温习了以下C#的索引器,写了一个比较基础的例子,以供正在学习索引器的一个参考。代码很简单,具体就是通过学生的姓名或学生的姓名和课程名,进行查询成绩。这里,主要是通过索引器的重载来实现的,对于初学者还是有一定的参考价值的吧。
代码:
Code
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class YourGrade
{
private string yname;//定义学生的姓名
private string course;//定义课程名
private float score;//定义成绩
public YourGrade(string yname,string course,float score) //利用构造函数初始化
{
this.yname = yname;
this.course = course;
this.score = score;
}
public string Yname
{
get { return yname; }
set { yname = value; }
}
public string Course
{
get { return course; }
set { course = value; }
}
public float Score
{
get { return score; }
set { score = value; }
}
}
class IndexerClass
{
System.Collections.ArrayList array;
public IndexerClass()
{
array = new System.Collections.ArrayList();
}
//定义索引器,通过姓名和课程名查询成绩
public float this[string _name, string _course]
{
get {
foreach (YourGrade ygrade in array)
{
if (ygrade.Course == _course && ygrade.Yname == _name)
{
return ygrade.Score;
}
}
return -1;//没有查找到,返回-1
}
set
{
array.Add(new YourGrade(_name,_course,value));
}
}
public System.Collections.ArrayList this[string _name]
{
get {
//定义一个临时ArrayList,用来存放查询结果
System.Collections.ArrayList temparray = new System.Collections.ArrayList();
foreach (YourGrade ygrade in array)
{
if (ygrade.Yname == _name)
{
temparray.Add(ygrade);
}
}
return temparray;
}
}
}
class TestIndex
{
static void Main()
{
IndexerClass index = new IndexerClass();
index["小燕子", "语文"] = 90.5f;
index["小燕子", "数学"] = 88.8f;
index["小燕子", "物理"] = 60f;
index["肥燕子", "语文"] = 78.5f;
Console.WriteLine("根据姓名模糊查询请选择:1;根据姓名和课程名查询请选择:2");
string selection = Console.ReadLine();
Console.WriteLine("请输入你要查询的学生名字:");
string inputname = Console.ReadLine();
switch (selection)
{
case "1":
if (index[inputname].Count > 0)//判读学生或成绩是否存在
{
Console.WriteLine("{0}同学,以下为你的成绩单:", inputname);
foreach (YourGrade y in index[inputname])
{
Console.WriteLine("{0}:{1}分", y.Course, y.Score);
}
}
else
{
Console.WriteLine("没有您要查找的学生或成绩!");
}
break;
case "2":
{
Console.WriteLine("请输入你要查询的课程名字:");
string inputcourse = Console.ReadLine();
if (index[inputname, inputcourse] != -1)
{
float rscore=index[inputname, inputcourse];
Console.WriteLine("{0}的{1}成绩为:{2}分", inputname, inputcourse,rscore);
}
else
{
Console.WriteLine("没有您要查找的学生或成绩!");
}
break;
}
}
}
}
}