一个简单的索引器的例子

   今天,抽空又温习了以下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;
}

}

}
}

}

转载于:https://www.cnblogs.com/shihenice/archive/2008/10/16/1312904.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值