索引器是什么
索引器是一种类型,使类的对象可以像数组那样使用,并且它还可以通过索引方式方便地访问类的数据信息的方法。
索引器与属性
索引器类似属性,属性是针对一个数据,而索引器是针对更多的数据,同时索引器的访问器采用的是参数。
索引器的作用
通常情况下,属性只能访问单一的字段(一个属性对一个字段进行封装),如果想访问多个数据成员,就需要使用索引器,索引器是类的特殊成员,它可以根据索引在多个数据成员中进行选择。能够让对象以类似数组的方式来存取。
索引器的格式
[修饰符]数据 类型 this [索引类型 index]
{
get
{
//返回参数值,往往根据索引的不同返回不同的字段,用选择语句
}
set
{
//设置隐式参数value给字段赋值,往往根据索引的不同给不同字段赋值,用选择语句
}
}
例1
class Program
{
static void Main(string[] args)
{
Student s = new Student();
s[1] = "张三";//给相应字段赋值
s[2] = "男"; //给相应字段赋值
s[3] = "1234567890";//给相应字段赋值
s.Say();
Console.ReadKey();
}
}
public class Student
{
private string name;
private string sex;
private string tel;
public string this[int index] //定义索引器
{
get//get访问器
{
switch (index)
{
case 1:
return name;
case 2:
return sex;
case 3:
return tel;
default:
//指定的参数已经超出有效值范围,即是index值不是上面的1、2、3时超出异常,终止switch
throw new ArgumentOutOfRangeException("index");
}
}
set
{
switch (index)
{
case 1:
name = value;
break;
case 2:
sex = value;
break;
case 3:
tel = value;
break;
default:
//指定的参数已经超出有效值范围,即是index值不是上面的1、2、3时抛出异常
throw new ArgumentOutOfRangeException("index");
}
}
}
public void Say()
{
//通过this[1]、this[2]、this[3]获取相应字段值
Console.WriteLine("我叫"+this[1]+",我是"+this[2]+"生,我的电话是:"+this[3]);
}
}
例2
class BankAccount
{
public int id;
public string name;
public int yuE;
public override string ToString()
{
return string.Format("id={0} ,name={1} , yuE={2}", id, name, yuE);
}
}
class Bank
{
private BankAccount[] accountList= new BankAccount[100];
private int n = 0;
public void Add(BankAccount ba)
{
accountList[n] = ba;
n++;
}
public BankAccount this[int id]
{
get
{
for (int i = 0; i < n; i++)
{
if (accountList[i].id == id)
{
return accountList[i];
}
}
return null;
}
set
{
for (int i = 0; i < n; i++)
{
if (accountList[i].id == id)
{
accountList[i] = value;
return;
}
}
}
}
}
class Program
{
static void Main(string[] args)
{
Bank bank = new Bank();
bank.Add(new BankAccount() { id = 1001, name = "小红", yuE = 0 });
bank.Add(new BankAccount() { id = 1002, name = "小黄", yuE = 50 });
bank.Add(new BankAccount() { id = 1003, name = "小蓝", yuE = 30 });
Console.WriteLine(bank[1001]);
}
}
索引器的特点:
1、索引器类型和其参数类型要和索引器本身一样是可访问的
2、索引器的签名由其形参的数量和类型组成,它不包括索引器类型或形参名。如果在同一个类中出现一个以上的所索引器,则必须有不同的签名
3、索引器值一般都是类的对象,所以不能将索引器的值作为ref或者out参数来传递。