每次看c# 时 看到索引器那块就停下来了,看不太懂,也没感到什么实用的地,
正所谓无知啊,今天学习了个简单 索引器
主程序代码:
static void Main(string[] args)
{
ProgramGroup group = new ProgramGroup(); //实例化对象
//Player[] name =new Player[2];//创建演员数组
创建演员对象并给属性赋值
//name[0]=new Player();
//name[0].Name="甄子丹";
//name[0].Role="叶问";
创建演员对象并给属性赋值
//name[1]=new Player();
//name[1].Name="熊黛林";
//name[1].Role="叶太太";
//group.Players = name; //把数组赋值给对象的属性
Console.WriteLine("演员阵容:");
//for (int i = 0; i < group.Players.Length; i++)
//{
// Console.WriteLine(group.Players[i].Name);//通过属性读取数组的值
//}
//group[0] = new Player();
//group[0].Name = "甄子丹";
//group[0].Role = "叶问";
//group[1] = new Player();
//group[1].Name = "熊黛林";
//group[1].Role = "叶太太";
//for (int i = 0; i < 2; i++)
//{
// Console.WriteLine(group[i].Name);
//}
group.SetPlayers(); //调用对象的方法给字段赋值
Console.WriteLine("甄子丹扮演" + group["甄子丹"].Role);
Console.WriteLine("熊黛林扮演" + group["熊黛林"].Role);
Console.ReadLine();
}
剧组类代码
class ProgramGroup //剧组类
{
//private Player[] players; //演员数组字段
//public Player[] Players //演员数组属性
//{
// get { return player; }
// set { player = value; }
//}
private Player[] players = new Player[2]; //演员数组字段
//public Player this[int index] //索引器,index是数组索引
//{
// get { return players[index]; }
// set { players[index]=value;}
//}
public Player this[string name] //通过演员名称查找的索引器
{
get
{
int i = 0;
for (; i < 2; i++) //循环查找演员
{
if (players[i].Name == name)
{
break;
}
}
if (i == 2)
{
return null; //没有找到返回空
}
else
{
return players[i]; //找到返回数组中的演员元素
}
}
}
public void SetPlayers() //给数组赋值
{
players[0] = new Player();
players[0].Name = "甄子丹";
players[0].Role = "叶问";
players[1] = new Player();
players[1].Name = "熊黛林";
players[1].Role = "叶太太";
}
}
class Player //演员类
{
private string name; //演员名称字段
public string Name //演员名称属性
{
get { return name; }
set { name = value; }
}
private string role; //扮演角色字段
public string Role //扮演角色属性
{
get { return role; }
set { role = value; }
}
}
感觉上面程序还是对索引器不太明白看下一个试试:
班级类:
class Squad //班级类
{
string name; //班级名称
public string Name
{
get { return name; }
set { name = value; }
}
int count; //学生数量
public int Count
{
get { return count; }
set { count = value; }
}
}
年纪类:
class Grade //年级类
{
string name; //年级名称
public string Name
{
get { return name; }
set { name = value; }
}
Squad[] squads = new Squad[2]; //班级数组
public Squad this[int index]
{
set { squads[index] = value; }
get { return squads[index]; }
}
}
主程序:
class Program
{
static void Main(string[] args)
{
Grade grade = new Grade(); //实例化对象
grade.Name = "S1";
grade[0] = new Squad(); //实例化数组元素对象
grade[0].Name = "S1T100"; //调用索引器赋值
grade[0].Count = 25;
grade[1] = new Squad();
grade[1].Name = "S1T101";
grade[1].Count = 29;
Console.WriteLine(grade.Name+"的班级有");
Console.WriteLine(grade[0].Name+"里有"+grade[0].Count+"人");
Console.WriteLine(grade[1].Name + "里有" + grade[1].Count + "人");
Console.ReadLine();
}
}