关于索引器

索引器这个东东,我也是最近才接触,一般所说的索引器,是指定义在某个类里面的一个类似属性的东西。索引器是.net中新的类成员。类似与类的属性。有些人干脆称呼它为带参数的属性。

索引器可以快速定位到类中某一个数组成员的单元。下面看看代码:

ContractedBlock.gifExpandedBlockStart.gifIndexer 
class indexerClass
{
private int[] arr=new int[100];
private string[] names=new string[100];
public int this[int index]
{
get
{
if (index < 0 || index >= 100)
{
return -1;
}
else
{
return arr[index];
}
}
set//索引器的get,set被编译器编译成get_item,sge_item方法。
{
if (index >=0 && index < 100)
{
arr[index]
=value;
}
}
}
public int this[string key]//索引器的参数也可是字符串等,不一定只能是int
{
get
{
return GetNumber(key);
}
}
public int GetNumber(string Gender)
{
if (Gender == "boy")
{
return 1;
}
else if (Gender == "girl")
{
return 0;
}
else
{
return -1;
}
}
}

索引器参数大多是int类型,但也可以是其他类型,如string。

static void Main(string[] args)
{
indexerClass indexerTest
= new indexerClass();
for (int i = 0; i < 10; i++)
{
indexerTest[i]
= i + 2; //对类的对象,可以直接像操作数组一样操作对象里面的数组。
}
for (int i = 0; i < 10; i++)
{
Console.WriteLine(indexerTest[i]);
}
Console.ReadKey();
}

转载于:https://www.cnblogs.com/YangFengHui/archive/2011/04/17/2018942.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值